1

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!

2
  • 2
    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.) Commented Jun 6, 2017 at 19:09
  • @jasonharper You're right-- nice catch! Your solution works, and I believe I understand your approach. Thank you! Commented Jun 6, 2017 at 20:09

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.