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.
>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]