How to reverse the bits of a number in JavaScript

2 Answers

0 votes
function reverseBits(num) {
    let count = 32; // 32-bits
    let reverseBits = 0;
 
    while (num) {
        reverseBits = (reverseBits << 1) | (num & 1);
        num >>>= 1;
        count--;
    }
 
    reverseBits <<= count;
    
    return reverseBits >>> 0; // Convert unsigned 32-bit integer
}

let num = 42;
console.log(("00000000000000000000000000000000" + num.toString(2)).substr(-32));
num = reverseBits(num);
console.log(("00000000000000000000000000000000" + num.toString(2)).substr(-32) + '\n');

num = 19;
console.log(("00000000000000000000000000000000" + num.toString(2)).substr(-32));
num = reverseBits(num);
console.log(("00000000000000000000000000000000" + num.toString(2)).substr(-32)); 




/*
run:

00000000000000000000000000101010
01010100000000000000000000000000

00000000000000000000000000010011
11001000000000000000000000000000

*/

 



answered Dec 14, 2023 by avibootz
0 votes
function reverseBits(n, width = 32) {
    // Convert to binary, reverse, convert back, and force unsigned 32‑bit
    const bin = n.toString(2).padStart(width, "0");
    const reversed = [...bin].reverse().join("");
    
    return (parseInt(reversed, 2) >>> 0);
}

function bits(n, width = 32) {
    // Convert to binary and group into 8‑bit chunks
    const bin = (n >>> 0).toString(2).padStart(width, "0");
    
    return bin.match(/.{8}/g).join(" ");
}

const a = 19;
const b = 3;

const ra = reverseBits(a);
const rb = reverseBits(b);

console.log("Original 19:", bits(a));
console.log("Reversed 19:", bits(ra));
console.log();
console.log("Original 3: ", bits(b));   
console.log("Reversed 3: ", bits(rb));


/*
run:

Original 19: 00000000 00000000 00000000 00010011
Reversed 19: 11001000 00000000 00000000 00000000

Original 3:  00000000 00000000 00000000 00000011
Reversed 3:  11000000 00000000 00000000 00000000

*/

 



answered Apr 4 by avibootz
...