【问题标题】:Casting a char valued 255 leads to an unsigned int value of 4294967295, what gives?转换一个值为 255 的 char 会导致一个 unsigned int 值为 4294967295,这是什么结果?
【发布时间】:2012-11-05 03:24:42
【问题描述】:

好的,这是我以前从未见过的奇怪问题:

#include <iostream>
int main()
{
  char testchar = 255;
  std::cout << (unsigned int)testchar << std::endl;
}

输出:

4294967295

到底是什么?似乎因为 char 是“满的”,所以当它生成新的 unsigned int 类型时,结果也是“满的”。这不是我记得的或我期望的结果。我希望 unsigned int 的值为 0x000000FF。谁能给我解释一下这里到底发生了什么?

系统:Ubuntu 12.04 64 位

g++ 版本:4.6.3

【问题讨论】:

  • 修改了问题标题以更加具体,以帮助搜索的人。

标签: c++ casting


【解决方案1】:

您的char 显然已签名。这意味着255 正在溢出char。由于您显然在 2 的补码机器上,因此 255 的位模式存储在 char 中(即所有位都已设置)。当解释为带符号的 8 位数字时,即为 -1。

然后那个值被符号扩展为32位int,给出32个1位(但相同的值,-1)。最后,该值被转换为unsigned int。根据通过减少模 232-1 完成的规则​​,它给出了最大可能的 32 位数字 (4294967295)。

【讨论】:

  • When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged. Otherwise: if the unsigned integer has greater size, the signed integer is first promoted to the signed integer corresponding to the unsigned integer; the value is converted to unsigned by adding to it one greater than the largest number that can be represented in the unsigned integer type. 引用自flash-gordon.me.uk/ansi.c.txt
  • 自从我用 C 编码以来已经有很长一段时间了。我从来没有考虑过默认情况下会签名一个字符 - 对我来说真的没有多大意义。现在我在定义指向无符号字符的指针时遇到问题 sigh 好吧,谢谢你的回答!
  • @Githlar:也许你只想先投射到unsigned char,然后再投射到unsigend int
猜你喜欢
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多