英文:
Convert ByteString into numpy array of 1s and 0s
问题
我想将一个字节字符串转换为一个由1和0组成的NumPy数组(即将该字节字符串的二进制值作为二进制值数组)。我该如何操作?
我尝试使用np.fromstring
和np.frombuffer
,但都没有得到我想要的结果。
英文:
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.
答案1
得分: 3
使用 numpy.unpackbits
。根据文档:
将 uint8 数组的元素解包到一个二进制值输出数组中。
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)
输出
[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]
英文:
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]
答案2
得分: 1
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论