连接位

Concatenating 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

但是当我打印温度时,它显示 0:

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

其实在我看来

temp = temp >> 8;

bitshifts away your entire temp value.

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);

打印 7273166300000100010101011100110000001111.


如果您想将输入保持为 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);

您似乎误解了数据的布局。 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 向左移动( 而不是 向右移动)并在 "normal" (未移位)地点:

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;