I have a numpy.array and would like to rotate its content one bit to the right. I want to perform this as efficient (in terms of execution speed) as possible. Also, please note that every element of the array is an 8-bit number (np.uint8). The rotation assumes that the array stores one big number which is split into chunks of size 8-bit, i.e., I'm not interested in rotating every 8-bit element by itself, but the whole array together.
Here is an example to remove any confusion:
a = numpy.array([0b00000000, 0b00000001])
# rotation should be performed globally
# i.e., the result should be
# rotate(a) == numpy.array([0b10000000, 0b00000000])
How I tried solving the problem?
Method #1: Convert the input array to binary representation and catenate the binary strings of the elements into one big string. Then pop the least significant bit and insert it ahead of the most significant bit. Finally, chop the big string into 8-bit chunks, convert every chunk into np.uint8, and store it in the corresponding position of the rotation result. I guess this solution is correct, but not efficient, especially if the input array is huge.
Method #2: I found it hard to explain the idea in words, so I'll just try convey it using the code fragment below:
# Let w be the input array
# read the least significant bits of every element in w
# and store them into another array lsb
mask = np.ones(shape=w.shape, dtype=np.int8)
lsb = np.bitwise_and(w,mask)
shiftedLsb = np.left_shift(np.roll(lsb, 1), 7)
rotW = np.right_shift(w,1)
rotationResult = np.bitwise_or(shiftedLsb, rotw)
My question: Is there a better way, in terms of execution speed, to implement this kind of rotation?
Thank you all.