bitReverse function

int bitReverse(
  1. int n,
  2. int bits
)

Rotate to left the bits of an int number n times

  • n : number
  • bits : number of rotations

Examples

print(bitReverse(1, 3));

/* output:
4
*/

Implementation

int bitReverse(int n, int bits) {
  var reversedN = n;
  var count = bits - 1;

  n >>= 1;
  while (n > 0) {
    reversedN = (reversedN << 1) | (n & 1);
    count--;
    n >>= 1;
  }

  return ((reversedN << count) & ((1 << bits) - 1));
}