问题
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?
回答1:
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.
回答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))
来源:https://stackoverflow.com/questions/7640993/pyserial-and-reading-binary-data