Created
February 3, 2013 17:55
-
-
Save tleunen/4702818 to your computer and use it in GitHub Desktop.
Function to reverse the bits of a given integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
}
reversed <<= 1
reversed += last
???
Did you try with 0x80000000?
Why only 31 iterations?
All have sense for positive numbers only.
But bitRev(1) is 0x80000000 which is negative.
bitRev(bitRev(1)) it's 0
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.
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
what about reversedN=N^((1<<bitsToRevers))-1)?
e.g. 010010 .xor. 111111 = 101101