Python: binascii.a2b_hex gives “Odd-length string”

后端 未结 4 646
挽巷
挽巷 2020-12-19 03:00

I have a hex value that I\'m grabbing from a text file, then I\'m passing it to a2b_hex to convert it to the proper binary representation. Here is what I have:



        
相关标签:
4条回答
  • 2020-12-19 03:15

    read() doesn't strip newlines. If there's a '\n' at the end of your file, it'll be in k1.

    Try binascii.a2b_hex(k1.strip()) or possibly binascii.a2b_hex(k1[:8]).

    0 讨论(0)
  • 2020-12-19 03:18

    Are you sure the file doesn't have something extra in it? Whitespace, for instance?

    Try k1.strip()

    0 讨论(0)
  • 2020-12-19 03:28

    I'm more interested what happens if you execute the following code:

    with open("./" + basefile + ".key") as key_file:
       key = key_file.read()
       print len(key), key
    

    Care to tell? There is probably some extra character you just don't see when printing. In these cases, make sure to print the length of the string.

    0 讨论(0)
  • 2020-12-19 03:33

    I suspect there is a trailing newline at the end of the file. Strip the string before passing it to binascii.

    Note there's now also a simpler spelling: k1.strip().decode('hex').

    0 讨论(0)
提交回复
热议问题