1

I'm trying to parse a binary file that has a combination of 1,2,4,8 byte integers and 4,8 byte floating points as well as varying strings with different encodings. How do I convert 4 bytes or 8 bytes to a floating point?

Is using the struct package the best way? if so, how do I use the struct package to get a floating point? with 4-bytes and 8-bytes

How could i do the same thing with a 2-byte or 4-byte integer? What i'm currently using is

int.from_bytes(binary_file.read(2), byteorder='little', signed=False)
int.from_bytes(binary_file.read(4), byteorder='little', signed=False)

Would it be more optimal to use struct for multiple ints and floats in succession?

1 Answer 1

1

The struct module is by far the most obvious/correct way to do this. If you read the docs you'd find all the format codes you need in a few seconds.

int.from_bytes is more general (handles arbitrary widths), but when you know the precise widths, you're likely better off with a struct; if you do it a lot for the same formats, using a preconstructed struct.Struct object will run faster than the module-level functions.

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.