Odd-length string error with binascii.unhexlify

13,935

Using the python console:

>>> help(binascii.unhexlify)

unhexlify(...)
    a2b_hex(hexstr) -> s; Binary data of hexadecimal representation.

    hexstr must contain an even number of hex digits (upper or lower case).
    This function is also available as "unhexlify()"

So the error is consistent. What you have to do is padding with '0' to have an even number:

>>> binascii.unhexlify('0%x' % n)
'\x01'
Share:
13,935

Related videos on Youtube

SpiderRico
Author by

SpiderRico

I once had an unicorn who disliked to eat coconuts on sunny weathers.

Updated on July 16, 2022

Comments

  • SpiderRico
    SpiderRico almost 2 years

    I'm trying to convert back and forth an ASCII string to its binary representation as follows.

    s=chr(0)*15 + chr(0x01)
    bst = bin(int(binascii.hexlify(s), 16))
    n = int(bst, 2)
    binascii.unhexlify('%x' % n) 
    

    However, I get the following error at the end which doesn't make much sense to me.

    1 binascii.unhexlify('%x' % n)

    TypeError: Odd-length string

    What's the issue and how can I solve it ?

  • PJ_Finnegan
    PJ_Finnegan over 2 years
    Padding at the beginning or at the end?