2014-09-04 82 views
-2
number = 240 

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

错误消息:Python的INT诅咒在while循环

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循环良好,比没有放错误?

+0

您没有包含错误。另外,如果你想拥有这个角色,使用'chr(number)'更容易。 – 2014-09-04 16:03:02

+0

你究竟在努力完成什么?防止样本错误的微不足道的解决方案不太可能解决您的实际问题。 – 2014-09-04 16:05:21

回答

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,当然。