2017-07-02 34 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;