Skip to content

Instantly share code, notes, and snippets.

@tleunen
Created February 3, 2013 17:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tleunen/4702818 to your computer and use it in GitHub Desktop.
Save tleunen/4702818 to your computer and use it in GitHub Desktop.
Function to reverse the bits of a given integer
function bitRev(N) {
var r = 0;
val = 0;
while(N > 0) {
val = N&1;
N >>= 1;
r += val&1;
r <<= 1;
}
r >>= 1;
return r;
}
@Vineg
Copy link

Vineg commented Sep 9, 2015

what about reversedN=N^((1<<bitsToRevers))-1)?
e.g. 010010 .xor. 111111 = 101101

@JacopoDaeli
Copy link

This doesn't work, but I appreciate the idea. My working solution is:

function bitRev (n) {
  let i = 0
  let reversed = 0
  let last
  while (i < 31) {
    last = n & 1
    n >>= 1
    reversed += last
    reversed <<= 1
    i++
  }
  return reversed
}

@mesterum
Copy link

mesterum commented Sep 4, 2017

reversed <<= 1
reversed += last

???
Did you try with 0x80000000?
Why only 31 iterations?
All have sense for positive numbers only.

@mesterum
Copy link

mesterum commented Sep 4, 2017

But bitRev(1) is 0x80000000 which is negative.

@mesterum
Copy link

mesterum commented Sep 4, 2017

bitRev(bitRev(1)) it's 0

@mesterum
Copy link

mesterum commented Sep 4, 2017

function bitRev (n) {
  let i = 0
  let reversed = 0
  let last
  while (i < 32) {
    last = n & 1
    n >>= 1
    reversed <<= 1
    reversed += last
    i++
  }
  return reversed
}

Test this.

@enkimute
Copy link

function reverse(bits) {   
    var  x=new Uint32Array(1); x[0]=bits; 
    x[0] = ((x[0] & 0x0000ffff) << 16) | ((x[0] & 0xffff0000) >>> 16);
    x[0] = ((x[0] & 0x55555555) << 1) | ((x[0] & 0xAAAAAAAA) >>> 1);
    x[0] = ((x[0] & 0x33333333) << 2) | ((x[0] & 0xCCCCCCCC) >>> 2);
    x[0] = ((x[0] & 0x0F0F0F0F) << 4) | ((x[0] & 0xF0F0F0F0) >>> 4);
    x[0] = ((x[0] & 0x00FF00FF) << 8) | ((x[0] & 0xFF00FF00) >>> 8);
    return x[0];
}

no loops .. no sign bit problems ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment