3

I've made sure the string is stripped and I still get the odd-length string issue. Can someone please tell me what I'm doing wrong?

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> toSend.decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string
>>> 
1
  • have you removed white spaces? Commented Dec 25, 2014 at 16:06

1 Answer 1

9

The spaces in the string are confusing the decode method. Your code will work if you remove them:

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> toSend.replace(' ', '').decode('hex')
'\xff\xf9\xff\x00\x00\xfa\xff\xf7\xff\xf4\xff\xf6\xff\xf7\xff\xf6\xff\xfd\xff\x05\x00\x03\x00\x06\x00\x05\x00\x04\x00\x06\x00\x06\x00\x03\x00\xfb\xff\x02\x00\x0b'
>>>

Or, if you must have them, use str.join and a list comprehension:

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> ' '.join([x.decode('hex') for x in toSend.split()])
'\xff \xf9 \xff \x00 \x00 \xfa \xff \xf7 \xff \xf4 \xff \xf6 \xff \xf7 \xff \xf6 \xff \xfd \xff \x05 \x00 \x03 \x00 \x06 \x00 \x05 \x00 \x04 \x00 \x06 \x00 \x06 \x00 \x03 \x00 \xfb \xff \x02 \x00 \x0b'
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

you can also use binascii binascii.a2b_hex(toSend.replace(' ', ''))
this helped me! Arrigato!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.