我必须连接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
最佳答案
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
。如果要将输入保留为
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);
关于c - 级联位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33966217/