C++中输出十六进制时-1显示为ffffffff的原因咨询
cout << hex << -1 output ffffffff on a 32-bit system? Great question! Let’s unpack this behavior clearly, tying it back to how integers are stored and how C++ streams handle hexadecimal output.
First, how is -1 stored in a 32-bit signed integer?
In most modern systems, signed integers use two's complement representation. For a 32-bit int, the value -1 is stored as a sequence of 32 1s in binary. When converted to hexadecimal, that's exactly ffffffff (each f represents four 1s in binary).
What happens when you use hex with cout?
The hex manipulator tells the output stream to switch its integer formatting mode. Unlike decimal (dec) mode, which respects the signedness of the integer (hence -1 shows up as -1), hexadecimal (and octal) mode treats the integer's bit pattern as an unsigned value.
This means:
- The stream doesn't check if the original number was signed or negative.
- It takes the exact binary bits stored in memory and converts them directly to hexadecimal, as if they belonged to an unsigned integer.
Since -1 in a 32-bit signed int is all 1s, interpreting those bits as an unsigned 32-bit integer gives the value 4294967295—which is ffffffff in hexadecimal.
Confirming the book's explanation
The book’s note ("输出八进制或十六进制数时,数字的位总是被解释为无符号的!即输出显示数字的位模式的八进制或十六进制形式") is spot-on. This behavior is intentional: hex/octal output is often used to inspect the raw bit patterns of values, so treating the bits as unsigned makes sense for that use case.
For example, on a 16-bit system, cout << hex << -1 would output ffff—again, matching the full bit pattern of -1 in 16 bits.
内容的提问来源于stack exchange,提问作者Ng.

