在Python中接收16位整数 [英] Receiving 16-bit integers in Python

查看:393
本文介绍了在Python中接收16位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm reading 16-bit integers from a piece of hardware over the serial port.

使用Python,我怎样才能使LSB和MSB正确,以及让Python明白它是一个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?

推荐答案

尝试使用 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中接收16位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆