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

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

오류 메시지 동안의 진수합니다 :파이썬 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 
?

+0

오류를 포함하지 않았습니다. 또한 캐릭터를 갖고 싶다면'chr (number)'를 사용하는 것이 훨씬 쉽습니다. –

+0

* 실제로 * 성취하려고하는 것은 무엇입니까? 샘플에서 오류를 방지하는 간단한 솔루션으로 실제 문제를 해결할 수 없습니다. –

답변

1

당신은이 단계를 너무 멀리하고 있습니다. number = 256 여기에 실패

hex 인코딩은 두 문자 16 진수 값을 처리 할 수 ​​있기 때문이다
>>> 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 

; 당신은 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 이하로 유지됩니다.