2017-07-02 70 views
-2

我想将一个int变量分成四个char变量,然后将它合并到一个int变量中。 但结果并不如预期。C++ biwise操作符或两个变量

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 

请帮帮我!

+0

结果如预期的那样,但是你的int c不能确保拟合4个字节。检查你的架构的int大小。 – Efren

+0

显然你的'char'是有符号的,所以当它转换为int时,它会得到符号扩展。 – harold

回答

-1

你有几种选择(记住int是不是unsigned int类型,我想你的意思是32位UINT,所以我会用另一种类型)

1.

union 
{ 
    uint32_t value; 
    uint8_t bytes[4]; 
}myunion; 

myunion.value = 0x11223344; 
and check muunion.bytes[xx] :) 

另一种解决方案

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;