Irbis
Irbis

Reputation: 13369

converting char to unsigned char

How the conversion works ? For example: Scope of char[-128, 127], scope of unsigned char[0, 255]

char x = -128;
unsigned char y = static_cast<unsigned char>(x);
cout<<y; //128

Why not 0 ?

Upvotes: 0

Views: 1189

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254421

Unsigned arithmetic, including conversion from signed types, is modular, with the modulus being 2n (where n is the number of bits).

Assuming that char has 8 bits, then -128 is congruent to 128, modulo 256; so that is the result of the conversion.

UPDATE: as noted in the comments, this assumes that -128 is a valid value for type char, which is not necessarily the case. char has a range of at least [0..127], and signed char at least [-127..127].

Upvotes: 6

Ben Voigt
Ben Voigt

Reputation: 283614

Unsigned arithmetic, and conversion to unsigned, takes place modulo 2N. You have an 8-bit character, so N is 8, and 2N is 256.

-128 and 128 are congruent modulo 256.

Here is the actual rule found in section 4.7 ([conv.integral]):

  • If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]
  • 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.

Upvotes: 5

Russell Borogove
Russell Borogove

Reputation: 19037

The conversion works by reinterpreting the same bit pattern in a different way, not by adding +128 to bias the scope. Read up on two's complement to learn more.

Upvotes: 1

Related Questions