有符号到无符号的转换
任何人都可以解释为什么下面的代码输出它的作用:
char c = -1;
cout << (c << 8) << endl;
cout << ((unsigned char) c << 8) << endl;
cout << (c << 24) << endl;
cout << ((unsigned char) c << 24) << endl;
输出:
-256
65280
-16777216
-16777216
我认为转换为无符号字符只会改变位的解释方式。然而,当向左移动8时,它改变了结果。奇怪的是,向左移动24时,情况似乎并非如此。
Can anyone explain why the following code outputs what it does:
char c = -1;
cout << (c << 8) << endl;
cout << ((unsigned char) c << 8) << endl;
cout << (c << 24) << endl;
cout << ((unsigned char) c << 24) << endl;
Output:
-256
65280
-16777216
-16777216
I thought casting to an unsigned char would simply change the way the bits get interpreted. However, it's changed the results when shifting to the left by 8. What's strange is that this doesn't seem to be the case when shifting to the left by 24.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在每种情况下,字符在转换之前都会提升为
int
。在您的平台上,
char
是有符号的,因此c
是-1
,但是(unsigned char)(c)
是 255。所以你会看到:
-1 << 8
255 << 8
-1 << 24
255 << 24
请注意,后者会溢出并换行(在您的平台上)。它不同于
255U << 24
,即 4278190080。要实现这一点,您必须说(unsigned int)(unsigned char) c << 24
。In each case, the character gets promoted to
int
before the shift.On your platform,
char
is signed, soc
is-1
, but(unsigned char)(c)
is 255.So you are seeing:
-1 << 8
255 << 8
-1 << 24
255 << 24
Note that the latter overflows and wraps (on your platform). It is different from
255U << 24
, which is 4278190080. To achieve that, you have to say(unsigned int)(unsigned char) c << 24
.