If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Re: unsigned char c = -1; // c has value 255, why is that?

Re: [RESOLVED] unsigned char c = -1; // c has value 255, why is that?

Originally Posted by Paul McKenzie

Your description is not the way that negative numbers are represented on most systems.

Look up two's complement.

Actually, Paul McKenzie's tip is not relevant here: two's complement does not come into play because the destination type is an unsigned integer type, whereas two's complement is one of the integer representation systems used for signed integer types. Rather, this conversion rule is relevant:

Originally Posted by C++11 Clause 4.7 - Integral conversions

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2**n 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 ]

Note that I substituted the superscript in the original text with ** to denote exponentiation. So, in your question, CHAR_BIT is 8 (which is usually the case), and 2**8 = 256. The source integer is -1. Hence, the resulting value is 255, since 255 is congruent to -1 (mod 256). Notice that this would be true regardless of the signed integer representation system.

Re: [RESOLVED] unsigned char c = -1; // c has value 255, why is that?

The internals is that whatever is the bit pattern of -1, the result will have the bit pattern of 255U for unsigned char. (Then again, since the compiler can determine the value to be stored at compile time, there is no need for a run time conversion to begin with.)

Originally Posted by vincegata

Btw, "C++11 Clause 4.7 - Integral conversions" is it from the C++ standard?

Yes, C++11 refers to the 2011 edition of the C++ Standard.

Originally Posted by vincegata

Where can I get?

You can obtain a PDF copy from the ANSI online store, at a price. Free draft versions are available online.