【发布时间】:2009-05-17 17:31:50
【问题描述】:
我正在通过串行端口从硬件中读取 16 位整数。
使用 Python,我怎样才能得到正确的 LSB 和 MSB,并让 Python 明白我正在摆弄它是一个 16 位有符号整数,而不仅仅是两个字节的数据?
【问题讨论】:
我正在通过串行端口从硬件中读取 16 位整数。
使用 Python,我怎样才能得到正确的 LSB 和 MSB,并让 Python 明白我正在摆弄它是一个 16 位有符号整数,而不仅仅是两个字节的数据?
【问题讨论】:
尝试使用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
【讨论】: