Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Bytes to Floating Point Numbers?

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?

like image 220
Cristian Avatar asked Aug 07 '08 22:08

Cristian


People also ask

How many bytes is a floating point?

Floating-point numbers use the IEEE (Institute of Electrical and Electronics Engineers) format. Single-precision values with float type have 4 bytes, consisting of a sign bit, an 8-bit excess-127 binary exponent, and a 23-bit mantissa.

What is a 4 byte floating point number?

4-byte float. float(18) defines a floating point type with at least 18 binary digits of precision in the mantissa. A 4‑byte floating point field is allocated for it, which has 23 bits of precision.

How do you convert bytes to integers?

A byte value can be interchanged to an int value using the int. from_bytes() function. The int. from_bytes() function takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes.


2 Answers

>>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' 
like image 196
tzot Avatar answered Oct 11 '22 03:10

tzot


Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write

>>> [x] = struct.unpack('f', b'\xdb\x0fI@') >>> x 3.1415927410125732 

If you have more floats then just write

>>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x0b\x01I4') >>> x 3.1415927410125732 >>> y 1.8719963179592014e-07 >>>  
like image 21
NDM Avatar answered Oct 11 '22 03:10

NDM