If I have the array:
{01101111,11110000,00001111} // {111, 240, 15}
The result for a 1 bit shift is:
{10110111,11111000,00000111} // {183, 248, 7}
The array size is not fixed, and the shifting will be from 1 to 7 inclusive. Currently I have the following code (which works fine):
private static void shiftBitsRight(byte[] bytes, final int rightShifts) {
assert rightShifts >= 1 && rightShifts <= 7;
final int leftShifts = 8 - rightShifts;
byte previousByte = bytes[0]; // keep the byte before modification
bytes[0] = (byte) (((bytes[0] & 0xff) >> rightShifts) | ((bytes[bytes.length - 1] & 0xff) << leftShifts));
for (int i = 1; i < bytes.length; i++) {
byte tmp = bytes[i];
bytes[i] = (byte) (((bytes[i] & 0xff) >> rightShifts) | ((previousByte & 0xff) << leftShifts));
previousByte = tmp;
}
}
Is there a faster way to achieve this than my current approach?
Right rotation of bits in C programming is supported using bitwise right shift operator >> . Similar to left shift, right shift operations also results in bit loss. On every shift operation the least significant bit is dropped.
There is only really one difference between the shift and rotate instructions: rotate cycles the bits around going out one side and coming in the other, while shift rotates the bits out one side or the other leaving the space where the rotated bits where either unchanged or zeroed.
The only way to find out is with thorough benchmarking, and the fastest implementations will vary from platform to platfrm. Use a tool like Caliper if you really need to optimize this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With