I have a datatype that’s more or less a character array. Each space in the array holds a char, which, as per my understanding, is a single byte (8 bits) of information. I need to be able to specify the char value through a binary string… for instance
char someChar = char(0b00110011);
What I don’t understand is why the max value I can specify is 0b0XXXXXXX, where I have to leave that MSB set to zero. If I try setting the char like so
char someChar = char(0b11111111);
I get a decimal value: -2147483648, which looks very much like overflow. So I don’t really get what’s going on here. If I call the sizeof() operator on char, I get an answer of 1 (one byte). Doesn’t that mean that I either get 0-255 if the char is unsigned, or -128-127 if the char is signed? Any advice/input would be appreciated.
In response to most of the comments — I converted it to an int before printing it out:
std::cerr << int(someChar)
Thanks to all for the thorough explanations 🙂
-2147483648 in binary is 10000000 00000000 00000000 01111111.
When you declare you
charin binary, you compiler interprets it as asigned char, which is the case for the most compilers. The leftmost bit is interpreted as the sign bit.Upon conversion to
int, the bit pattern of the value is copied, therefore the seven rightmost bits, and the sign bit is moved to the MSB of the 32-bit block.You have two main problems here :
someCharto be unsigned. If that’s the case, you should tell it to your compiler :unsigned char someChar = unsigned char(0b11111111);int. If it’s not needed, there is likely a way to printsomeCharfor what it is really, i.e. asigned char.