简体   繁体   English

Numpy:5 位到 integer(Python)

[英]Numpy: 5 bits to integer (Python)

I have an array of bits.我有一个位数组。

Input: array([0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0])输入: array([0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0])

And I need to transform it into an array of integer, reading 1 unsigned integer from 5 bits.我需要将其转换为 integer 的数组,从 5 位读取 1 个无符号 integer。

Output: array([1, 19, 14]) Output: array([1, 19, 14])

Because: ( 00001 -> 1 , 10011 -> 19 , 01110 -> 14 )因为: ( 00001 -> 1 , 10011 -> 19 , 01110 -> 14 )

Can I do it with numpy (or plain Python)?我可以用 numpy (或纯 Python)来做吗?

What if I need 6 bits to unsigned integer?如果我需要 6 位无符号 integer 怎么办?

Reshape into an Nx5 array, and use a broadcasted multiplication and a sum to reduce along the length-5 axis:重塑为 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)

this is a bit complicated.这有点复杂。 Mabye it´sa better way to do it. Mabye 这是一个更好的方法。 but it works.但它有效。 this solution is without numpy.此解决方案没有 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]

I would suggest using a factor array.我建议使用因子数组。 With this factor array you go over the data and multiply each chunk with this factor array and calculate its sum (which is the interrepesentation of the bit pattern)使用这个因子数组,您可以对数据进行 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)

this gives numpy the possibilty to use vector instructions for the array mulitplication and the horizontal sum over the chunks.这使 numpy 可以使用向量指令进行数组乘法和块上的水平和。

PS: There might be a better way for chunk = data[i*bits:(i+1)*bits] PS: chunk = data[i*bits:(i+1)*bits]可能有更好的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM