C++双算子或双变量
我想把一个int变量拆分成四个char变量,然后把它合并成一个int变量。 但结果并不像预期的那样C++双算子或双变量,c++,bitwise-operators,C++,Bitwise Operators,我想把一个int变量拆分成四个char变量,然后把它合并成一个int变量。 但结果并不像预期的那样 int a = 123546; //0x1e29a char b[4]{ 0 }; b[0] = a; //0x9a b[1] = a >> 8; //0xe2 b[2] = a >> 16; //0x01 b[3] = a >> 24; //0x0 int c = 0; c
int a = 123546; //0x1e29a
char b[4]{ 0 };
b[0] = a; //0x9a
b[1] = a >> 8; //0xe2
b[2] = a >> 16; //0x01
b[3] = a >> 24; //0x0
int c = 0;
c = b[3]; //0x0
c = ((c << 8) | b[2]); //0x01
c = ((c << 8) | b[1]); //0xffffffe2 -> What is it??
c = ((c << 8) | b[0]); //0xffffff9a
请帮帮我 您有几个选项记住int不是无符号int,我想您指的是32位uint,所以我将使用另一种类型 一, 另一个解决方案
void ToBytes(uint32_t value, uint8_t *bytes)
{
int i;
for(i = 0; i < 4; i++)
{
byte[i] = value & 0xff;
value >> = 8;
}
}
结果与预期一样,但int c不能确保适合4个字节。检查您的体系结构的int大小。显然,您的字符是有符号的,所以当转换为int时它会得到符号扩展。
void ToBytes(uint32_t value, uint8_t *bytes)
{
int i;
for(i = 0; i < 4; i++)
{
byte[i] = value & 0xff;
value >> = 8;
}
}
uint32_t value;
uint8_t *bytes = &value;