我正在尝试测试从串行端口接收的数据,但似乎无法得到正确的结果。我需要检查数据包中收到的第一个字节是否为 0xBE:
#ser is instance of pyserial serial object
data=ser.read(5)
print "serial RX: " + binascii.b2a_hex(data)
if data[0] != 0xBE:
print"wrong value"
始终打印:
serial RX: beef000008
wrong value
即使二进制到 ascii 打印显示已收到正确的值。
在这个非常基本的任务中我哪里出错了?
谢谢, 罗宾。
最佳答案
Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.
所以我测试了:
>> bytes(0xbe) == 0xbe
False
但如果将其转换为 int:
>> int(bytes(0xbe)) == 0xbe
True
如这个stackoverflow question显示,bytes类型包含在 [PEP-3137 3] 中]。它就像一个bytearray对于 python3,但只是 python2 中 str
的别名.
因此,基本上,在执行 python2 代码时,只需将 pyserial 的输出视为 str
即可。
关于python - 测试来自串行端口的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17254881/