Python循环中的int int到hex

时间:2014-09-04 16:02:04

标签: python

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循环好,而不是没有put错误?

1 个答案:

答案 0 :(得分: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编码只能处理两个字符的十六进制值;你必须用0填充这个数字:

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

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

while number < 256:

使用chr() function要容易,而不是将数字格式化为十六进制然后解码:

data_hex = chr(number)

演示:

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

当然number保持在255以下。