0

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?

5
  • 4
    split into 5-element lists, then compute the values by using powers of 2. Try that, post your attempt if you can't do it. Commented May 12, 2020 at 8:50
  • This seems odly specific. Just kindly asking: Is this for somekind of assigment? Commented May 12, 2020 at 8:51
  • @Ackdari I'm parsing a Minecraft file, where BlockStates are stored this way. There are other implementation, but are based on bit manipulating, i was hoping to find a simpler way with numpy. Commented May 12, 2020 at 8:54
  • @Jean-FrançoisFabre i = array([0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0]) list(map(lambda x: sum([pow(2, len(x) - p -1) * v for p,v in enumerate(x)]), numpy.split(i, len(i)/5))) Commented May 12, 2020 at 9:12
  • okay, in your question, please Commented May 12, 2020 at 9:13

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

Comments

2

this is a bit complicated. Mabye it´s a 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]

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.