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 C++

1 Answer

0 votes
#include <iostream>
#include <bitset>
 
void print_bits(unsigned int n) { 
    std::bitset<32> bits(n);
    std::cout << bits << '\n';
}
 
unsigned int reverseBits(unsigned int num) {
    unsigned int total_bits = sizeof(num) * 8;
    unsigned int reversed_bits = 0;
 
    for (unsigned int i = 0; i < total_bits; i++) {
        if ((num & (1 << i))) {
            reversed_bits |= 1 << ((total_bits - 1) - i);
        }
    }
 
    return reversed_bits;
}
 
int main()
{
    unsigned int num = 42;
    print_bits(num);
    num = reverseBits(num);
    print_bits(num);
    std::cout << "\n";
     
    num = 19;
    print_bits(num);
    num = reverseBits(num);
    print_bits(num);
     
    return 0;
}
 
 
 
 
/*
run:
 
00000000000000000000000000101010
01010100000000000000000000000000
 
00000000000000000000000000010011
11001000000000000000000000000000
 
*/

 



answered Dec 13, 2023 by avibootz

Related questions

2 answers 170 views
1 answer 124 views
124 views asked Dec 12, 2023 by avibootz
1 answer 126 views
1 answer 108 views
1 answer 102 views
1 answer 97 views
1 answer 108 views
...