将ByteString转换为由1和0组成的NumPy数组

huangapple go评论51阅读模式
英文:

Convert ByteString into numpy array of 1s and 0s

问题

我想将一个字节字符串转换为一个由1和0组成的NumPy数组(即将该字节字符串的二进制值作为二进制值数组)。我该如何操作?

我尝试使用np.fromstringnp.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)

huangapple
  • 本文由 发表于 2023年2月14日 04:39:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定