Reputation: 69
I am struggling with a number-format problem in Python 3.6. My goal is to convert binary data from a file into printable decimal numbers. As an example, I need to convert two little-endian bytes in the form of a byte string...
b'\x12\00'
into its big-endian binary form...
0000000000010010
and finally to its 16-bit fixed-point Q15 decimal number form...
(1 / 4096) + (1 / 16384) = 0.00030517578 (basically, we've made the 2 bytes above human-readable)
In my failed attempts, the struct.unpack function seemed promising, but my low-level / number representation experience just isn't very mature at the moment.
Failed Attempt:
struct.unpack('<h', b'\x12\x00') # Yields (18,)
The above code gets me "18", which would be fine if the bytes represented an integer, but they do not.
Any help / advice would be appreciated. Thank you!
Upvotes: 1
Views: 1874
Reputation: 69
Answered by @jasonharper in the question comments--
The bytes do represent an integer - which has been shifted by 15 bits. Divide by 32768 (2**15) to get the actual Q15 value. (This doesn't match the value you calculated, but that's because you did the math wrong - the two set bits actually have place values of 1/2048 and 1/16384.)
I achieved the proper value via the following code--
struct.unpack('<h', b'\x12\x00')[0] / (2**15)
Upvotes: 1