连接位

时间:2015-11-28 00:00:07

标签: c bits

我必须连接int的位。例如:

unsigned char byte1 = 0x0F;   // 00001111
unsigned char byte2 = 0xCC;   // 11001100
unsigned char byte3 = 0x55;   // 01010101
unsigned char byte4 = 0x04;   // 00000100

连接后,结果应为:

00000100010101011100110000001111 

我尝试过像:

unsigned int temp = 0;
temp = temp | byte1; //the result should be 00001111 for now

temp = temp >> 8;
byte2 = byte2 << 8;
temp = temp | byte2; //the result should be 1100110000001111 for now

temp = temp >> 8;
byte3 = byte3 << 8;
temp = temp | byte3; //the result should be 010101011100110000001111 for now

temp = temp >> 8;
byte4 = byte4 << 8;
temp = temp | byte4; //the result should be 00000100010101011100110000001111

但是当我打印temp时,它会显示0:

printf("%d", temp) //===> gives 0

3 个答案:

答案 0 :(得分:3)

实际上在我看来

temp = temp >> 8;

比特移除你的整个临时值。

答案 1 :(得分:3)

unsigned int byte1 = 0x0F; // 00001111; //byte1
unsigned int byte2 = 0xCC; // 11001100; //byte2
unsigned int byte3 = 0x55; // 01010101; //byte3
unsigned int byte4 = 0x04; // 00000100; //byte4

unsigned int temp = (byte1) | (byte2 << 8) | (byte3 << 16) | (byte4 << 24);
printf("%u", temp);

打印72731663 00000100010101011100110000001111。{/ p>

如果您想将输入保持为unsigned char,则结果相同:

unsigned char byte1 = 0x0F; // 00001111; //byte1
unsigned char byte2 = 0xCC; // 11001100; //byte2
unsigned char byte3 = 0x55; // 01010101; //byte3
unsigned char byte4 = 0x04; // 00000100; //byte4

unsigned int temp = byte4;
temp <<= 8;
temp |= byte3;
temp <<= 8;
temp |= byte2;
temp <<= 8;
temp |= byte1;
printf("%u", temp);

答案 2 :(得分:1)

您似乎误解了数据的布局。 temp = temp >> 8总是会移出您刚添加的内容:

uint32_t temp = 0; // 00000000 00000000 00000000 00000000
temp |= byte1;     // 00000000 00000000 00000000 00001111
temp = temp >> 8;  // 00000000 00000000 00000000 00000000
// and so on...

当与较大的数字组合时,字节在左侧(不在右侧)被零扩展,因此将它们向右移动将再次移除它们。

有两种明显的写法:

第一种方法是将字节左移到正确的位置,然后将它们转换为结果:

uint32_t temp = 0;     // 00000000 00000000 00000000 00000000
temp |= byte1;         // 00000000 00000000 00000000 00001111
temp |= (byte2 <<  8); // 00000000 00000000 11001100 00001111
temp |= (byte3 << 16); // 00000000 01010101 11001100 00001111
temp |= (byte4 << 24); // 00000100 01010101 11001100 00001111

另一种方法是将temp向左移动(向右移动)并在其“正常”(未移位)位置将字节移入其中:< / p>

uint32_t temp = 0; // 00000000 00000000 00000000 00000000
temp |= byte4;     // 00000000 00000000 00000000 00000100
temp = temp << 8;  // 00000000 00000000 00000100 00000000
temp |= byte3;     // 00000000 00000000 00000100 01010101
temp = temp << 8;  // 00000000 00000100 01010101 00000000
temp |= byte2;     // 00000000 00000100 01010101 11001100
temp = temp << 8;  // 00000100 01010101 11001100 00000000
temp |= byte1;     // 00000100 01010101 11001100 00001111

两者都可以简明扼要地写成,如:

uint32_t temp = (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1;

uint32_t temp = ((byte4 << 8 | byte3) << 8 | byte2) << 8 | byte1;