6

When the device I am communicating with sends binary data, I can recover most of it. However, there always seem to be some bytes missing, replaced by non-standard characters. For instance, one individual output looks like this:

\xc4\xa5\x06\x00.\xb3\x01\x01\x02\x00\x00\x00=\xa9

The period and equals sign should be traditional bytes in hexadecimal format (I confirmed this in another application). Other times I get other weird characters such as ')' or 's'. These characters usually occur in the exact same spot (which varies with the command I passed to the device).

How can I fix this problem?

2 Answers 2

12

Are you displaying the output using something like this?:

print output

If some of your bytes happen to correspond with printable characters, they'll show up as characters. Try this:

print output.encode('hex')

to see hex values for all your bytes.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This is almost two years old, but it helped me out.
print ' '.join(map(lambda x:x.encode('hex'),output)) # this separates bytes with spaces
2

At first I liked @RichieHindle answer, but when I tried it the hex bytes were all bunched together. To get a friendlier output, I use

print ' '.join(map(lambda x:x.encode('hex'),output))

4 Comments

print(' '.join(map(lambda x:x.encode('hex',s)))) TypeError: map() requires at least two args Never used lambdas, do you have an explanation?
In RichieHindle's answer, the hex encoding is done on all the bytes of the string "output", to produce one long hex number. What my function does, is take the bytes individually from output and converts the hex, so I get the hex value of each byte, separated by spaces. lambda is an easy way to make a simple (unnamed) function for map to apply to each element of the list in the second argument to map. Learn "map" and "lambda" and you'll never go back to your old way of doing things. Trust me.
Years later, but if you found this answer and saw @chwi comment, the right-paren is misplaced in the comment.
So print(' '.join(map(lambda x:x.encode('hex'), s))) then :)

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.