我正在通过串行端口从一个硬件读取 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
关于python - 在 Python 中接收 16 位整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/875046/