Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a binary string into IEEE-754 single precision - Python

I have a binary matrix which I create by NumPy. The matrix has 5 rows and 32 columns.

array([[1, 1, ..., 1, 1],
   [0, 1, ..., 0, 1],
   [1, 1, ..., 0, 1],
   [0, 0, ..., 1, 0],
   [1, 1, ..., 0, 1]])

I convert a matrix rows into a string, and next to integer.

str = ''.join(map(str,array[0])).replace(' ','') 
int(str, base=2)

How can I convert the string into the float (float32 - IEEE-754 single)?

like image 402
Heniek Kowalski Avatar asked Aug 07 '26 22:08

Heniek Kowalski


1 Answers

Using struct.pack, struct.unpack:

>>> a = [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0,
...      1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1]
>>> i = int(''.join(map(str, a)), 2)
>>> import struct
>>> struct.unpack('f', struct.pack('I', i))[0]
1.100000023841858

import struct

matrix = array(...)

st_i = struct.Struct('I')
st_f = struct.Struct('f')
float_values = [
    st_f.unpack(st_i.pack(int(''.join(map(str, a)), 2)))
    for a in matrix
]

NOTE: According to the byteorder of the array, you need to prepend <, > before the structure format.

BTW, overwriting str is not a good idea. You cannot use str function/type after the assignment.

like image 58
falsetru Avatar answered Aug 10 '26 11:08

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!