gpt4 book ai didi

连接位

转载 作者:行者123 更新时间:2023-12-04 11:53:47 24 4
gpt4 key购买 nike

我必须连接 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);

关于连接位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com