代码之家  ›  专栏  ›  技术社区  ›  Clayton

如何获取C++中字符的整数值?

  •  4
  • Clayton  · 技术社区  · 17 年前

    我想将存储在32位无符号整数中的值,放入四个字符中,然后将每个字符的整数值存储在一个字符串中。

    我认为第一部分是这样的:

    char a = orig << 8;
    char b = orig << 8;
    char c = orig << 8;
    char d = orig << 8;
    
    5 回复  |  直到 17 年前
        1
  •  10
  •   friol    17 年前

    假设“orig”是一个包含值的32位变量。

    我想你想做这样的事情:

    unsigned char byte1=orig&0xff;
    unsigned char byte2=(orig>>8)&0xff;
    unsigned char byte3=(orig>>16)&0xff;
    unsigned char byte4=(orig>>24)&0xff;
    
    char myString[256];
    sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4);
    

    顺便说一句,我不确定这是否总是正确的。( 编辑 :事实上,它是endian正确的,因为位移位操作不应受到endianness的影响)

        2
  •  10
  •   LogicStuff    10 年前

    如果确实要先提取单个字节,请执行以下操作:

    unsigned char a = orig & 0xff;
    unsigned char b = (orig >> 8) & 0xff;
    unsigned char c = (orig >> 16) & 0xff;
    unsigned char d = (orig >> 24) & 0xff;
    

    unsigned char *chars = (unsigned char *)(&orig);
    unsigned char a = chars[0];
    unsigned char b = chars[1];
    unsigned char c = chars[2];
    unsigned char d = chars[3];
    

    或者使用无符号长字符和四个字符的并集:

    union charSplitter {
        struct {
            unsigned char a, b, c, d;
        } charValues;
    
        unsigned int intValue;
    };
    
    charSplitter splitter;
    splitter.intValue = orig;
    // splitter.charValues.a will give you first byte etc.
    

    a , b , c d

        3
  •  4
  •   LogicStuff    10 年前

    使用 union . (根据要求,这里是示例程序。)

        #include <<iostream>>
        #include <<stdio.h>>
        using namespace std;
    
        union myunion
        {
           struct chars 
           { 
              unsigned char d, c, b, a;
           } mychars;
    
            unsigned int myint; 
        };
    
        int main(void) 
        {
            myunion u;
    
            u.myint = 0x41424344;
    
            cout << "a = " << u.mychars.a << endl;
            cout << "b = " << u.mychars.b << endl;
            cout << "c = " << u.mychars.c << endl;
            cout << "d = " << u.mychars.d << endl;
        }
    

    正如James提到的,这是特定于平台的。

        4
  •  1
  •   LogicStuff    10 年前

    char a = orig & 0xff;
    orig >>= 8;
    char b = orig & 0xff;
    orig >>= 8;
    char c = orig & 0xff;
    orig >>= 8;
    char d = orig & 0xff;
    

    0x10111213 进入 "16 17 18 19" 还是怎样

        5
  •  0
  •   Ates Goral    17 年前

    对于十六进制:

    sprintf(buffer, "%lX", orig);
    

    sprintf(buffer, "%ld", orig);
    

    使用 snprintf 以避免缓冲区溢出。