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?

0

2 Answers 2

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

Comments

-1

The f.read(4) part is your issue here.

file.read reads at most size bytes and returns [the bytes]. See https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files.

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

You can get inspiration from here: Python f.read not reading the correct number of bytes

1 Comment

No it's not. b'\xbc\xe9\x11e' is 4 bytes. If it weren't, unpack would throw an error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.