【问题标题】:Receiving 16-bit integers in Python在 Python 中接收 16 位整数
【发布时间】:2009-05-17 17:31:50
【问题描述】:

我正在通过串行端口从硬件中读取 16 位整数。

使用 Python,我怎样才能得到正确的 LSB 和 MSB,并让 Python 明白我正在摆弄它是一个 16 位有符号整数,而不仅仅是两个字节的数据?

【问题讨论】:

    标签: python integer


    【解决方案1】:

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

    【讨论】:

    • 或“!h”表示“网络字节序”,以防您不想记住它是大字节序。
    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多