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

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

char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
有帮助吗?

解决方案

如果你真的想先提取单个字节:

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.

更新:正如Friol指出的那样,解决方案2和3不是字节序无关的;哪些字节 a b c d 表示取决于CPU架构。

其他提示

让我们说“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正确的,因为bitshift操作不应受字节顺序的影响)

希望这有帮助。

使用 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;
    }

正如詹姆斯所说,这是特定于平台的。

不完全:

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

不完全确定您的意思“将每个值的整数值存储到字符串中。您是否希望将 0x10111213 转入&quot; 16 17 18 19&quot; ,或者是什么?

对于十六进制:

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

对于十进制:

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top