Python中整数转字节未以十六进制表示的原因咨询
Got it, let's clear up this confusion—your question hits on a common point where Python's byte string display behavior can trip people up, but it's totally logical once you see what's going on.
The Core Issue: Python Prioritizes Readable Display Over Uniform Hex
When you convert an integer to a byte string with to_bytes(), Python doesn't always show every byte as a \xHH hex escape. Instead:
- If a byte corresponds to a printable ASCII character (like letters, numbers, symbols), it will display as that character directly (e.g., byte 65 shows as
b'A'). - If a byte corresponds to a common ASCII control character with a standard shorthand escape (like newline
\nfor byte 10, carriage return\rfor byte 13, tab\tfor byte 9), it will use that shorthand instead of the\xHHformat. - Only bytes that don't fall into either category get displayed as
\xHHhex escapes.
Let's Break Down Your Example
You converted the integer 13 to a 2-byte big-endian string:
(13).to_bytes(2, byteorder='big') # Output: b'\x00\r'
Here's why you see \r instead of \x0D:
- The integer 13 in hex is
0xD, which maps to the ASCII carriage return (CR) character. Python recognizes this control character and uses its standard shorthand escape\rinstead of the generic\x0Dhex escape. - The first byte is 0, which has no shorthand escape, so it shows as
\x00.
But rest assured: the actual byte values are exactly what you expect. To confirm, you can inspect individual bytes or get the raw hex representation:
byte_str = b'\x00\r' print(byte_str[1]) # Output: 13 (the integer value, which is 0xD in hex) print(byte_str.hex()) # Output: '000d' (raw hex of the entire byte string)
Why Reverse Conversion Works Perfectly
When you use int.from_bytes() to convert back, Python doesn't care about the display format—it reads the actual numerical value of each byte. The \r is just a human-readable representation; under the hood, that byte is still 13 (0xD), so the reverse conversion gives you the correct integer every time.
Quick Tips to See Raw Hex When You Need It
If you want to bypass Python's readable display and see the full hex representation every time:
- Use the
hex()method on the byte string, as shown above. - Iterate over the byte string and format each byte as hex:
byte_str = b'\x00\r' print(['{:02x}'.format(b) for b in byte_str]) # Output: ['00', '0d']
内容的提问来源于stack exchange,提问作者ScottMcC

