Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert ByteString into numpy array of 1s and 0s

I am wanting to turn a bytestring, for example b'\xed\x07b\x87S.\x866^\x84\x1e\x92\xbf\xc5\r\x8c' into a numpy array of 1s and 0s (i.e. the binary value of this bytestring as an array of binary values).

How would I go about doing this?

I tried using np.fromstring and np.frombuffer but neither did what I wanted.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use numpy.unpackbits. Per the docs:

Unpacks elements of a uint8 array into a binary-valued output array.

import numpy as np

b = b'\xed\x07b\x87S.\x866^\x84\x1e\x92\xbf\xc5\r\x8c'

bits_array = np.unpackbits(np.frombuffer(b, dtype=np.uint8))
print(bits_array)

outputs

[1 1 1 0 1 1 0 1 0 0 0 0 0 1 1 1 0 1 1 0 0 0 1 0 1 0 0 0 0 1 1 1 0 1 0 1 0
 0 1 1 0 0 1 0 1 1 1 0 1 0 0 0 0 1 1 0 0 0 1 1 0 1 1 0 0 1 0 1 1 1 1 0 1 0
 0 0 0 1 0 0 0 0 0 1 1 1 1 0 1 0 0 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 0 0 0 1 0
 1 0 0 0 0 1 1 0 1 1 0 0 0 1 1 0 0]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading