我正在通过串口从一块硬件读取16位整数。
使用Python,我如何正确地获得LSB和MSB,并让Python理解它是一个我正在摆弄的16位有符号整数,而不仅仅是两个字节的数据?
答案 0 :(得分:21)
尝试使用struct模块:
import struct
# read 2 bytes from hardware as a string
s = hardware.readbytes(2)
# h means signed short
# < means "little-endian, standard size (16 bit)"
# > means "big-endian, standard size (16 bit)"
value = struct.unpack("<h", s) # hardware returns little-endian
value = struct.unpack(">h", s) # hardware returns big-endian