1

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?

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, though I am not sure if this is correct. The first number 3701687786 should be converted to 11011100 10100011 01000101 11101010 according to here. This is not the same as out[0, :32]-
A, probably, I got the little indian order. For big indian, try [None, None, ::-1]
Ok, it looks correct now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.