Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to do a right bit rotation/circular shift on a byte array

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?

like image 284
mota Avatar asked Mar 22 '12 15:03

mota


People also ask

How do you rotate a bit right?

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.

What is the difference between bit shifting and bit rotating?

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.


1 Answers

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.

like image 102
Louis Wasserman Avatar answered Sep 22 '22 04:09

Louis Wasserman