I have a binary file that I have to parse and I’m using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
>>> import struct
>>> struct.pack('f', 3.141592654)
b'xdb<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="621a52042b22">[email protected]</a>'
>>> struct.unpack('f', b'xdb<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="641c54022d24">[email protected]</a>')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'x00x00x80?x00x00<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c541c1c6c">[email protected]</a>x00<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfb7ffff8f">[email protected]</a>@x00x00<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="631b5b5323">[email protected]</a>'
Method 2
Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write
>>> import struct
>>> [x] = struct.unpack('f', b'xdb<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f78fc791beb7">[email protected]</a>')
>>> x
3.1415927410125732
If you have more floats then just write
>>> import struct
>>> [x,y] = struct.unpack('ff', b'xdb<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f276f39161f">[email protected]</a>x0bx01I4')
>>> x
3.1415927410125732
>>> y
1.8719963179592014e-07
>>>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0