在Python中接收16位整数

12 投票
1 回答
18589 浏览
提问于 2025-04-15 11:39

我正在通过串口从一块硬件读取16位的整数。

我想用Python来处理这些数据,怎么才能正确获取最低有效位(LSB)和最高有效位(MSB),并让Python明白我在处理的是一个16位的有符号整数,而不仅仅是两字节的数据呢?

1 个回答

25

试试使用 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

撰写回答