我想取存储在32位无符号int中的值,将其放入四个字符中,然后将每个字符的整数值存储在一个字符串中.
我认为第一部分是这样的:
char a = orig << 8; char b = orig << 8; char c = orig << 8; char d = orig << 8;
Gabriele D'A.. 10
假设"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);
顺便说一句,我不确定这是否总是正确的.(编辑:确实,它是字节序正确的,因为bitshift操作不应受字节顺序的影响)
希望这可以帮助.
假设"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);
顺便说一句,我不确定这是否总是正确的.(编辑:确实,它是字节序正确的,因为bitshift操作不应受字节顺序的影响)
希望这可以帮助.
如果你真的想先提取单个字节:
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];
或者使用unsigned long和four chars的并集:
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架构.