unsigned char limited to 127 on osx lion?
I am facing a strange issue, working on my mac osx lion (under xcode4/clang, though it is reproducible with gcc4.2).
It seems, that I can not assign any value above 127 for a unsigned char variable. So, when I assign
v = (unsigned char) 156;
or, simply
std::cout << (unsigned char) 231 << std::endl;
my program does not produce any output.
When I run this code
std::cout << "Unsigned chars range up to " << UCHAR_MAX << std::endl;
I get the following output:
Unsigned chars range up to 255
However, when I run something like this, the program generates outputs up to some different arbitrary value (such as c = 114, c = 252, etc etc) each time. for(unsigned char c = 0; c < CHAR_MAX; c++) std::cout << "c = " << 2*c << std::endl;
Changing the CHAR_MAX to UCHAR_MAX, the program ends without an output again :(
Thanks in advance
cout
is converting the numeric value to a character from the character set (Well, it's attempting to ... when you don't see anything it's not a valid character for your charset, and technically it's the terminal that's deciding this).
Cast it to unsigned int
instead.
Edit to add: ildjarn makes a very valid point in his comment to your question; if you ran this in the debugger you'd see that the value was indeed what you expected.
What symbol are you expecting to see to represent character (unsigned char)231
? On most systems, these are extended characters that need special terminal settings to be displayed as anything coherent if even visible.
Try this:
unsigned char testChar = (unsigned char)231;
unsigned int testInt = (unsigned int)testChar;
std::cout << testInt << std::endl;
The value of unsigned char
is not limited to 127, however standard ASCII is only 7 bits (so 128 values). Any value above 127 does not represent any character (unless you use some kind of extended ASCII), so nothing is printed.
上一篇: C ++ zlib压缩浮点结构