Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of char c = 255 converted to int

My question is about a paragraph in Stroustrup's book the C++ programming language, 4th edition. He brings an example of having

char c = 255; // 255 is ‘‘all ones,’ ’ hexadecimal 0xFF
int i = c;

and explanation of how it will be converted on machines where char is either signed or unsigned.

What will be the value of i? Unfortunately, the answer is undefined. On an implementation with 8-bit bytes, the answer depends on the meaning of the ‘‘all ones’’ char bit pattern when extended into an int. On a machine where a char is unsigned, the answer is 255. On a machine where a char is signed, the answer is −1.

My question is why it will be -1, doesn't it depends on what representation of binary numbers is used on machine? Wouldn't it be 0(-0) if it uses ones' complement and -1 if two's complement?

like image 342
Karen Melikyan Avatar asked Feb 15 '19 11:02

Karen Melikyan


2 Answers

Quoting C++03 4.7/3:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

Assuming bytes are 8 bits, this means that in theory you get one of the following:

  • -127 if signed magnitude computer.
  • -0 if one's complement computer.
  • -1 if two's complement computer.

The former two barely exist in the real world.

like image 93
Lundin Avatar answered Oct 23 '22 22:10

Lundin


(In the case char is signed 8 bit type) 255 is not a representable value. Converting an unrepresentable value to a signed type results in an implementation defined value (until C++20). So, Stroustrup is simplifying a bit in this step; the result could be anything in this case as far as the standard is concerned.

But assuming the sign representation is two's complement, it is likely that the value will be congruent with 255 modulo 28 (in the future C++20 standard, this becomes a guarantee). The value that is congruent with 255 modulo 28 and is representable is -1.

Wouldn't it be 0(-0) if it uses ones' complement

Probably (until C++20). But ones' complement is archaic and hardly used anymore. So, as I said, it seems Stroustrup seems to have chosen to simplify the explanation and assumed two's complement. Or maybe he had the future standard in mind when he wrote it; Or maybe the standard change was proposed to make his book correct :)

like image 26
eerorika Avatar answered Oct 23 '22 21:10

eerorika