Receiving 16-bit integers in Python

后端 未结 1 1047
囚心锁ツ
囚心锁ツ 2021-01-02 07:26

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

Using Python, how can I get the LSB and MSB right, and make Python understand that it is

相关标签:
1条回答
  • 2021-01-02 08:07

    Try using the struct module:

    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
    
    0 讨论(0)
提交回复
热议问题