Prismatic
Prismatic

Reputation: 3348

C++ char definition from binary string and overflow

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 :)

Upvotes: 1

Views: 1797

Answers (2)

Useless
Useless

Reputation: 67713

char is signed in this case, so setting the top bit will give a negative value. Use unsigned char if you don't want to worry about positive/negative values.

As for the negative integer value - please show how you're converting/displaying the char.


NB. You can use signed char or unsigned char to tell the compiler explicitly what you want.

Upvotes: 1

slaphappy
slaphappy

Reputation: 6999

-2147483648 in binary is 10000000 00000000 00000000 01111111.

When you declare you char in binary, you compiler interprets it as a signed 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 :

  • First, it seems that you except someChar to be unsigned. If that's the case, you should tell it to your compiler : unsigned char someChar = unsigned char(0b11111111);
  • Second, the way you put it to the console (which is unknown to us) apparently involves a conversion to int. If it's not needed, there is likely a way to print someChar for what it is really, i.e. a signed char.

Upvotes: 0

Related Questions