简体   繁体   English

转换值为255的char导致unsigned int值为4294967295,是什么给出的?

[英]Casting a char valued 255 leads to an unsigned int value of 4294967295, what gives?

OK, this is a strange issue that I've been having that I've never seen before: 好的,这是我以前从未见过的一个奇怪的问题:

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

Output: 输出:

4294967295

What in the heck? 到底是什么? It seems that because the char is "full," when it generates the new unsigned int type the result is "full" as well. 似乎因为char是“full”,当它生成新的unsigned int类型时,结果也是“full”。 This is not the result I remember or that I expect. 这不是我记得或我期望的结果。 I would expect the unsigned int to have a value of 0x000000FF. 我希望unsigned int的值为0x000000FF。 Can anybody explain to me exactly what's going on here? 任何人都可以向我解释这里到底发生了什么吗?

System: Ubuntu 12.04 64-bit 系统:Ubuntu 12.04 64位

g++ version: 4.6.3 g ++版本:4.6.3

Your char is apparently signed. 你的char显然是签了名。 That means the 255 is overflowing the char . 这意味着255溢出了char Since you're apparently on a 2's complement machine, the bit-pattern of the 255 is being stored in the char (ie, all bits are set). 因为你显然是在2的补码机器上,所以255的位模式存储在char (即,所有位都被置位)。 When interpreted as a signed 8-bit number, that's -1. 当解释为带符号的8位数时,则为-1。

Then that value is sign-extended out to a 32-bit int , giving 32 1 bits (but the same value, -1 ). 然后将该值符号扩展为32位int ,给出32位(但相同的值, -1 )。 Finally, that value is converted to unsigned int . 最后,该值转换为unsigned int According to the rules that's done by reduction modulo 2 32 -1, which gives the largest possible 32-bit number (4294967295). 据至由还原模2 32 -1,这给最大可能的32位数字(4294967295)进行的规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM