Python int 在循环中转换为十六进制

-2 投票
1 回答
547 浏览
提问于 2025-04-19 20:35
number = 240

while (number < 257):
    data = format(number, 'x')
    data_hex = data.decode("hex")
    number = number + 1

错误信息:

    data_hex = data.decode("hex")
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string

我该如何让一个while循环运行得更好,避免出现错误呢?

1 个回答

1

你这一步走得有点远了;number = 256 在这里会出错:

>>> format(256, 'x')
'100'
>>> format(256, 'x').decode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string

这是因为 hex 编码只能处理 两个字符的十六进制值;你需要在这个数字前面加零:

>>> format(256, '04x').decode('hex')
'\x01\x00'

或者限制你的循环,不要产生 256:

while number < 256:

其实用 chr() 函数 会简单得多,而不是先把数字格式化为十六进制再解码:

data_hex = chr(number)

示例:

>>> format(255, 'x').decode('hex')
'\xff'
>>> chr(255)
'\xff'

当然,前提是 number 必须小于 255。

撰写回答