Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to reverse the bits of a number in JavaScript

1 Answer

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

Related questions

1 answer 126 views
1 answer 108 views
1 answer 97 views
1 answer 108 views
1 answer 101 views
101 views asked Dec 13, 2023 by avibootz
1 answer 124 views
124 views asked Dec 12, 2023 by avibootz
3 answers 136 views
...