简体   繁体   中英

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])

And I need to transform it into an array of integer, reading 1 unsigned integer from 5 bits.

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

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

Can I do it with numpy (or plain Python)?

What if I need 6 bits to unsigned integer?

Reshape into an Nx5 array, and use a broadcasted multiplication and a sum to reduce along the length-5 axis:

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. but it works. this solution is without 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)

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.

PS: There might be a better way for chunk = data[i*bits:(i+1)*bits]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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