Python3.4 convert int16_t string to signed float

317 Views Asked by At

I apologise if this question has already been answered here. My searches have turned up similar questions but I have been unsuccessful in applying them to my situation.

I receive data via serial communication as two 16bit hexadecimal bytes. Now represented by two python integers. [48822, 15938]

These bytes represent a signed floating point variable. i.e. [48822, 15938]-->[0xbeb6, 0x3e42]-->[0x3e42beb6]-->[0.190181]

How would I complete this conversion in python3.4?

2

There are 2 best solutions below

2
Tim Roberts On BEST ANSWER
>>> import struct
>>> f = struct.unpack('f',struct.pack('HH', 48822,15938))[0]
>>> f
0.19018062949180603
>>> 

You can use *lst to convert your list to parameters for struct.pack.

0
Mad Physicist On

If you're getting a significant amount of data this way, you may want to consider using numpy. You can pack a buffer of dtype np.uint16 and view the contents directly as np.float32 without copying any data:

n = 1
buffer = np.zeros(2 * n, dtype=np.uint16)
floats = buffer.view(np.float32)
buffer[:2] = [48822, 15938]
print(floats)