Ng.
Ng.

Reputation: 111

Output of hexadecimal in C++

This is an example in "A Complete Guide to Programming in C++" (Ulla Kirch-Prinz & Peter Prinz)

Example:

cout << dec << -1 << " " << hex << -1;

This statement causes the following output on a 32-bit system:

-1 ffffffff

Could anyone please explain why the second output is ffffffff?

I have trouble with the explanation in the book that says:

When octal or hexadecimal numbers are output, the bits of the number to be output are always interpreted as unsigned! In other words, the output shows the bit pattern of a number in octal or hexadecimal format.

Upvotes: 0

Views: 1300

Answers (3)

Bathsheba
Bathsheba

Reputation: 234635

The text you've highlighted is saying that the output is equivalent to

cout << dec << -1 << " " << hex << (unsigned)-1;

In a 2's complement system (which any desktop PC is these days), the bit pattern for -1 has all bits set to 1.

For a 32 bit int therefore, the output will be ffffffff.

Finally, note that if int (and therefore unsigned) are 32 bits, the type of the literal 0xffffffff is unsigned.


References:

http://en.cppreference.com/w/cpp/language/integer_literal

https://en.wikipedia.org/wiki/Two%27s_complement

Upvotes: 0

rustyx
rustyx

Reputation: 85256

That's because most modern machines use two's complement signed integer representation.

In two's complement, the highest bit is used as a sign bit. If it is set, the number is considered negative, and to get its absolute (positive) value you need to subtract it from 2N, i.e. take it's two's complement.

If you had an 8-bit number, 00000001, it's two's complement would be 100000000-00000001 = 11111111 (or 0xFF hex). So -1 is represented as all 1's in binary form.

It's a very convenient system because you can perform arithmetic as if the numbers were unsigned (letting them overflow), then simply interpret the result as signed, and it will be correct.

Upvotes: 5

bobra
bobra

Reputation: 625

compiler implement negative numbers for signed variables in ths following way, if the highest bit is true, your number implements like (VALUE_RANGE - variable)

here is an example on 8 bit numbers, i hope you will expand it.

char   0 1 2 ... 10 ... 126 127 -128 -127 -126 ... -10 ...  -2   -1

uchar  0 1 2 ... 10 ... 126 127  128  129  130 ... 246 ... 254  255

hex    0 1 2 ... A  ...  7E  7F   80   81   82 ...  F6 ...  FE   FF    

Upvotes: 0

Related Questions