Assigning negative value to char
Why does the following code print "?" ?
Also how can -1 be assigned to an unsigned char
?
char test;
unsigned char testu; //isn't it supposed to hold values in range 0 - 255?
test = -1;
test开发者_Python百科u = -1;
cout<<"TEST CHAR = "<<test<<endl;
cout<<"TESTU CHAR = "<<testu<<endl;
unsigned
simply affects how the internal representation of the number (char
s are numbers, remember) is interpreted. So -1
is 1111 1111
in two's complement notation, which when put into an unsigned char
changes the meaning (for the same bit representation) to 255.
The question mark is probably the result of your font/codepage not mapping the (extended) ASCII value 255 to a character it can display.
I don't think <<
discerns between an unsigned char and a signed char, since it interprets their values as ASCII codes, not plain numbers.
Also, it depends on your compiler whether char
s are signed or unsigned by default; actually, the spec states there's three different char types (plain, signed, and unsigned).
When you assign a negative value to an unsigned variable, the result is that it wraps around. -1 becomes 255 in this case.
I don't know C or C++, but my intuition is telling me that it's wrapping -1 to 255 and printing ÿ
, but since that's not in the first 128 characters it prints ?
instead. Just a guess.
To test this, try assigning -191
and see if it prints A
(or B
if my math is off).
Signed/unsigned is defined by the use of the highest order bit of that number. You can assign a negative integer to it. The sign bit will be interpreted in the signed case (when you perform arithmetics with it). When you treat it it like a character it will simply take the highest order bit as if it was an unsigned char and just produce an ASCII char beyond 127 (decimal):
unsigned char c = -2;
is equivalent to:
unsigned char c = 128;
WHEN the c is treated as a character. -1 is an exception: it has all 8 bits set and is treated as 255 dec.
精彩评论