我正在玩位移。我正在尝试使用32位int,将每个字节保存在char数组中,然后重构int。它按我认为的方式工作,除了右边的第二个字节似乎有最低位切换。我的代码是:
int main() {
char paus[2];
char b[4] = "abc";
int c = 6104;
int d = 0xcccccccc;
printf("c in hex: %x\n",c);
printf("d in hex: %x\n",d);
printf("b[0]: %x\nb[1]: %x\n",b[0]&0xff,b[1]&0xff);
printf("b[2]: %x\nb[3]: %x/n",b[2]&0xff,b[3]&0xff);
printf("\n");
b[0] = c >> 24;
b[1] = (c >> 16) & 0xff;
b[2] = (c >> 8) & 0xff;
b[3] = c & 0xff;
printf("b[0]: %x\nb[1]: %x\n",b[0]&0xff,b[1]&0xff);
printf("b[2]: %x\nb[3]: %x\n",b[2]&0xff,b[3]&0xff);
printf("\n");
d = (d << 8) + 0x15;
printf("d in hex: %x\n",d);
d = (d << 8) + b[1];
printf("d in hex: %x\n",d);
d = (d << 8) + b[2];
printf("d in hex: %x\n",d);
d = (d << 8) + b[3];
printf("d in hex: %x\n",d);
fgets(paus,2,stdin);
return 0;
}
输出结果为:
c in hex:17d8
d十六进制:cccccccc
b [0]:61
b [1]:62
b [2]:63
b [3]:0
b [0]:0
b [1]:0
b [2]:17
b [3]:d8
d in hex:cccccc15
d为十六进制:cccc1500
d十六进制:cc150017
d十六进制:150016d8
一切都有意义,除了为什么右边的第二个字节从位移17变为16左8位? 15和00字节一直传输,为什么17字节会改变?谢谢!
答案 0 :(得分:0)
问题是您的编译器设置为将char
视为signed char
。试试这个:
d = (d << 8) + (unsigned char)b[3];
printf("d in hex: %x\n",d);
(您可能希望对其他实例执行相同的操作。)
或者,您可以更改d
的声明:
unsigned char b[4] = "abc";