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
charis apparently signed. That means the255is overflowing thechar. Since you’re apparently on a 2’s complement machine, the bit-pattern of the 255 is being stored in thechar(i.e., 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 tounsigned int. According to the rules that’s done by reduction modulo 232-1, which gives the largest possible 32-bit number (4294967295).