SamTheProgrammer
SamTheProgrammer

Reputation: 1185

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.

Upvotes: 1

Views: 94

Answers (2)

Frank Yellin
Frank Yellin

Reputation: 11240

I don't believe numpy gives you a way to do this directly.

You can do this in several steps:

x = np.frombuffer(data, dtype=np.ubyte)
y = np.array([1, 2, 4, 8, 16, 32, 64, 128])

z = np.sign(x[:,None] & y[None,:])

This now gives you a 16x8 array of 0's and 1s with your data. You can resize it if you want flat data.

z.resize(len(data) * 8)

Upvotes: 1

Brian61354270
Brian61354270

Reputation: 14413

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]

Upvotes: 3

Related Questions