1

I got a binary file written in java.I want to read the file with python,and convert every 4 bytes to a float.

the first 4 bytes is bce9 1165,but I read it is b'\xbc\xe9\x11e' by the code

with open(filename, "rb+") as f:
    f.read(4)

it's different!

Then I convert it by struct.unpack('f',data1).but I got the wrong float. the wrong float is 4.30659236383095e+22. but it's truly -0.028450677 so how to decode it?

XiaXuehai
  • 590
  • 1
  • 6
  • 19

2 Answers2

2

Your float is encoded in big-endian format. To decode it, give struct.unpack the '>f' format string (the > explicitly tells it to use big-endian format, rather than your system's native byte order):

>>> struct.unpack('>f', b'\xbc\xe9\x11e')
(-0.028450677171349525,)
Blckknght
  • 100,903
  • 11
  • 120
  • 169
0
f.read(4) is your issue here 

file.read reads at most size bytes and returns.Python Docs

You'll have to create a wrapper function to read exact bytes.

You can get inspiration from here :Check link

Pavan K
  • 4,085
  • 8
  • 41
  • 72