[英]Convert a byte array to single bits in a array [Python 3.5]
我正在尋找一個操作女巫轉換我的字節數組:
mem = b'\x01\x02\xff'
在這樣的事情:
[ [0 0 0 0 0 0 0 1]
[0 0 0 0 0 0 1 0]
[1 1 1 1 1 1 1 1] ]
這些是我嘗試過的操作:
import numpy as np
mem = b'\x01\x02\xff' #define my input
mem = np.fromstring(mem, dtype=np.uint8) #first convert to int
#print(mem) give me "[ 1 2 255]" at this piont
mem = np.array(['{0:08b}'.format(mem[b]) for b in mem]) #now convert to bin
data= np.array([list(mem[b]) for b in mem]) #finally convert to single bits
print(data)
此代碼將在第 4 行崩潰.. IndexError: index 255 is out of bounds for axis 0 with size 9
否則,它會在第 5 行崩潰.. IndexError: too many indices for array
這些是我的問題:
為什么hex轉int后空格數不一樣?
這就是我下一次從 int 轉換為 bin 失敗的原因嗎?
最后,我的list
操作有什么問題?
感謝您的幫助! :)
使用解包位:
>>> import numpy as np
>>> mem = b'\x01\x02\xff'
>>> x = np.fromstring(mem, dtype=np.uint8)
>>> np.unpackbits(x).reshape(3,8)
array([[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1]], dtype=uint8)
來自help(np.unpackbits)
:
解包(...)
解包位(myarray,軸=無)將 uint8 數組的元素解包為二進制值輸出數組。
myarray
每個元素代表一個位域,該位域應該被解包成一個二進制值的輸出數組。 輸出數組的形狀是一維(如果axis
為無)或與輸入數組相同的形狀,並沿指定的軸進行解包。
要解決 IndexError 您可以使用numpy.ndindex
:
import numpy as np
mem = b'\x01\x02\xff' #define my input
mem = np.fromstring(mem, dtype=np.uint8) #first convert to int
#print(mem) give me "[ 1 2 255]" at this piont
mem=np.array(['{0:07b}'.format(mem[b]) for b in np.ndindex(mem.shape)])
data= np.array([list(mem[b]) for b in np.ndindex(mem.shape)]) #finally convert to single bits
print(data)
輸出:
[['0', '0', '0', '0', '0', '0', '1'] ['0', '0', '0', '0', '0', '1', '0']
['1', '1', '1', '1', '1', '1', '1', '1']]
我很確定您的代碼的問題在於您假設列表中每個項目中的int
將變為 8 位(因此,在您的假設中, 2
將返回00000010
)。 但它沒有( 2
= 10
),這搞砸了你的代碼。
對於你的最后兩行,我認為這應該沒問題:
data = [list(str(bin(x))[2:]) for x in mem]
for a in range(len(data)):
while len(data[a]) < 8:
data[a] = "0" + data[a]
str(bin(x))[2:]
轉換為二進制(因為它為1
返回0b1
,您需要使用[2:]
來獲得1
)。
最后一段代碼是用額外的0
來“填充”你的數字。
mem = b'\x01\x02\xff'
[[int(digit) for digit in "{0:08b}".format(byte)] for byte in mem]
輸出:
[[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.