Home > front end >  Python converting binary data to 64-bit floating point. "error: unpack requires a buffer of 4 b
Python converting binary data to 64-bit floating point. "error: unpack requires a buffer of 4 b

Time:12-15

I am trying to convert a binary file with the hex representation: 4187D78400000000. This has a 64 bit floating point value (big-endian) of 50000000.

However when I try to unpack the structure using:

sample_freq = byte[8:16]
print(sample_freq)
sample_freq = struct.unpack('f', byte[8:16])
print(sample_freq)

I get the following error:

b'A\x87\xd7\x84\x00\x00\x00\x00'
Traceback (most recent call last):

  File "C:XXXXX", line 32, in <module>
    sample_freq = struct.unpack('f', byte[8:16])

error: unpack requires a buffer of 4 bytes

CodePudding user response:

If you use the character f to unpack the value, it will try to read a 32 bits float number. To decode a 64 bits value you should read it as a double using character d. So this should be the correct way to do it:

sample_freq = byte[8:16]
print(sample_freq)
sample_freq = struct.unpack('d', byte[8:16])
print(sample_freq)
  • Related