Heniek Kowalski
Heniek Kowalski

Reputation: 133

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)?

Upvotes: 3

Views: 2241

Answers (2)

Jaime
Jaime

Reputation: 67427

It is kind of convoluted, but you can get the same result as your original code in a single liner as:

In [61]: a = np.random.randint(2, size=(5, 32))

In [62]: for x in a:
   ....:             x_t = ''.join(map(str, x))
   ....:             print x_t, int(x_t, 2)
   ....:
11111111100000111010110110101100 4286819756
01001000110000111001000100011110 1220776222
10101111100100010000111010100111 2945519271
01101111101100011111101001100110 1873934950
11001000110101000111010100000011 3369366787

In [63]: np.packbits(a.reshape(-1, 8)).reshape(-1, 4)[:, ::-1].copy().view(np.uint32)
Out[63]:
array([[4286819756],
       [1220776222],
       [2945519271],
       [1873934950],
       [3369366787]], dtype=uint32)

Upvotes: 1

falsetru
falsetru

Reputation: 369134

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.

Upvotes: 6

Related Questions