Home > Back-end >  Numpy array of u32 to binary bool array
Numpy array of u32 to binary bool array

Time:10-28

I have an array:

a = np.array([[3701687786,  458299110, 2500872618, 3633119408],
              [2377269574, 2599949379,  717229868,  137866584]], dtype=np.uint32)

How do I convert this to an array of shape (2, 128) where 128 represents the binary value for all the numbers in each row (boolean dtype) ?

I can sort of get the bytes by using list comprehension:

b''.join(struct.pack('I', x) for x in a[0])

But this is not quite right. How can I do this using numpy?

CodePudding user response:

You can do bitwise and with the powers of 2:

vals = (a[...,None] & 2**np.arange(32, dtype='uint32')[[None,None,::-1])

out = (vals>0).astype(int).reshape(a.shape[0],-1)

# test
out[0,:32]

Output:

array([1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,
       0, 1, 1, 1, 1, 0, 1, 0, 1, 0])
  • Related