[英]Numpy: 5 bits to integer (Python)
我有一個位數組。
輸入: array([0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0])
我需要將其轉換為 integer 的數組,從 5 位讀取 1 個無符號 integer。
Output: array([1, 19, 14])
因為: ( 00001
-> 1
, 10011
-> 19
, 01110
-> 14
)
我可以用 numpy (或純 Python)來做嗎?
如果我需要 6 位無符號 integer 怎么辦?
重塑為 Nx5 數組,並使用廣播乘法和求和沿長度 5 軸減少:
temp = arr.reshape((-1, 5))
temp = temp * [16, 8, 4, 2, 1] # you can use *= here if you don't need to preserve the input
result = temp.sum(axis=1)
這有點復雜。 Mabye 這是一個更好的方法。 但它有效。 此解決方案沒有 numpy。
s = ""
arr = []
for n, i in enumerate(lst):
mod = n % 5
s += str(i)
if mod == 4:
s += " "
for item in s.split():
arr.append(int(str(item), 2))
print(arr)
Output:
[1, 14, 19]
我建議使用因子數組。 使用這個因子數組,您可以對數據進行 go 並將每個塊與該因子數組相乘並計算其總和(這是位模式的相互表示)
def bitToInt(data, bits):
factor_arr = np.ones(bits)
for i in range(bits):
factor_arr[0:i] = factor_arr[0:i] * 2
res = []
for i in range(int(len(data)/bits)):
chunk = data[i*bits:(i+1)*bits]
res.append(int((chunk * factor_arr).sum()))
return np.array(res)
這使 numpy 可以使用向量指令進行數組乘法和塊上的水平和。
PS: chunk = data[i*bits:(i+1)*bits]
可能有更好的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.