3

I have one array like [4, 255, 16], with dtype = int8. I want to rotate it left but like a binary rotate.

I want my array to be as explained below:

000001001111111100010000

After rotate left 2 bits, it will be:

000100111111110001000000

In decimal like [17, 252, 64]

2
  • Did you try anything already? It is always better when we have some code as starting point. Commented Mar 25, 2019 at 12:52
  • 2
    Shouldn't 000100111111110001000000 be [19, 252, 64] ? Commented Mar 25, 2019 at 13:07

2 Answers 2

3

You can use deque from collections if you want to rotate it nicely,

>>> from array import array
>>> from collections import deque
>>> x = array('l', [4, 255, 16])
>>> x
array('l', [4, 255, 16])
>>> z = ''.join([format(y, 'b').zfill(8) for y in x.tolist()])
>>> z
'000001001111111100010000'
>>> d = deque(z)
>>> d.rotate(-2)
>>> ''.join(d)
'000100111111110001000000'
>>> k = ''.join(d)
>>> [int(k[i:i+8],2) for i in range(0, len(k), 8)]
[19, 252, 64]
Sign up to request clarification or add additional context in comments.

4 Comments

Why use array? z = ''.join([format(y, 'b').zfill(8) for y in x]) if x= [4, 255, 16] works just fine.
@DavidBuck I just wanted to show the user, if he already has an array. And the question, started with, I have one array like [4, 255, 16], with dtype = int8. Which is array.array('l', [4, 255, 16]) :)
Thanks for the interesting answers. Though, can be remove .tolist() ?
@GrijeshChauhan Sure, he could have just started with a simple list
1

You want to rotate the array as if it were one long integer.

The solution below converts the array into one long integer, that is simply a Python int, rotates it with bitwise arithmetic, then write it back in the array.

Code

from array import array

def shift_left(arr, shift=1):
    if not arr:
        return

    long = 0
    itemsize = arr.itemsize * 8
    bit_length = len(arr) * itemsize
    item_bits = (1 << itemsize) - 1
    bits = (1 << bit_length) - 1

    # Convert the array to a long integer
    for i, x in enumerate(reversed(arr)):
        long |= x << (i * itemsize)

    # Left part of the | shifts the long left and drops the overflow
    # Right part of the | adds the last bits at the start of the long
    long = (long << shift & bits) | long >> (bit_length - shift)

    # Write back the long integer in the array
    for i in range(1, len(arr) + 1):
        arr[-i] = long & item_bits
        long >>= itemsize

Example

arr = array('B', [4, 255, 16])
shift_left(arr, shift=2)
print(arr)

Output

array('B', [19, 252, 64])

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.