Bit manipulation 有符号到无符号转换
有人能解释一下为什么下面的代码会输出它的功能吗:Bit manipulation 有符号到无符号转换,bit-manipulation,unsigned,signed,Bit Manipulation,Unsigned,Signed,有人能解释一下为什么下面的代码会输出它的功能吗: char c = -1; cout << (c << 8) << endl; cout << ((unsigned char) c << 8) << endl; cout << (c << 24) << endl; cout << ((unsigned char) c << 24) << endl; 我
char c = -1;
cout << (c << 8) << endl;
cout << ((unsigned char) c << 8) << endl;
cout << (c << 24) << endl;
cout << ((unsigned char) c << 24) << endl;
我认为转换为无符号字符只会改变位的解释方式。然而,当向左移动8时,结果会发生变化。奇怪的是,当向左移动24时,情况似乎并非如此。在每种情况下,字符都会在移动前提升到
int
在您的平台上,char
是有符号的,因此c
是-1
,但是(unsigned char)(c)
是255
所以你看到了:
-1
-256 65280 -16777216 -16777216