Вы хотите повернуть массив, как если бы он был одним длинным целым числом.
Приведенное ниже решение преобразует массив в одно длинное целое число, то есть просто Python int
, вращает его с помощью побитовой арифметики и записывает обратно в массив.
код
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
Пример
arr = array('B', [4, 255, 16])
shift_left(arr, shift=2)
print(arr)
Выход
array('B', [19, 252, 64])