pythonbinascii

Python - Binascii Error while unhexlify


I am reading out a file, calculate the ord-number which can be used together with the ord() function.

After that I unhexlify this number to get the byte representation of this character, because I work with non-ASCII characters and write these into a file.

Everything is working fine until I'm is reading out an "CR" better known as carriage return.

My Program raises the error:

Traceback (most recent call last):
  File "C:\Users\#######", line xx:
    x2 = binascii.unhexlify(format(Echr,"x"))
binascii.Error: Odd-length string

Do you got any idea why this error raises and how to fix this? Till now jut the CR is raising this error.


Solution

  • You are trying to pass an odd-length string to unhexlify, which can only handle hex characters in pairs.

    If you produced your hex from an integer value in the range 0-255, make sure to pad your hex string with a 0:

    x2 = binascii.unhexlify(format(Echr, "02x"))
    

    The 02x formatted tells the format() function to fit your number in to a field of width 2, with leading zeros if the actual value is shorter:

    >>> format(13, '02x')
    '0d'
    >>> binascii.unhexlify(format(10, '02x'))
    '\r'
    

    Using binascii.unhexlify together with format() is rather a roundabout way to create the bytes however. You can skip all that and go straight to the chr() function, which produces a character from an integer:

    >>> chr(13)
    '\r'