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. This is not the result I remember or that I expect. I would expect the unsigned int to have a value of 0x000000FF. Can anybody explain to me exactly what's going on here?
System: Ubuntu 12.04 64-bit
g++ version: 4.6.3
Your char
is apparently signed. That means the 255
is overflowing the 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). When interpreted as a signed 8-bit number, that's -1.
Then that value is sign-extended out to a 32-bit int
, giving 32 1 bits (but the same value, -1
). Finally, that value is converted to unsigned int
. According to the rules that's done by reduction modulo 2 32 -1, which gives the largest possible 32-bit number (4294967295).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.