在 Python 中接收 16 位整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/875046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:02:20 来源:igfitidea点击:
Receiving 16-bit integers in Python
提问by ASk
I'm reading 16-bit integers from a piece of hardware over the serial port.
我正在通过串行端口从硬件中读取 16 位整数。
Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data?
使用 Python,我怎样才能正确获得 LSB 和 MSB,并使 Python 理解它是一个我正在摆弄的 16 位有符号整数,而不仅仅是两个字节的数据?
回答by ASk
Try using the structmodule:
尝试使用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