You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中整数转字节未以十六进制表示的原因咨询

Understanding Python's Byte String Display vs. Actual Byte Values

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 \n for byte 10, carriage return \r for byte 13, tab \t for byte 9), it will use that shorthand instead of the \xHH format.
  • Only bytes that don't fall into either category get displayed as \xHH hex 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 \r instead of the generic \x0D hex 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:19:29