What is the efficient way to reverse bits of a number?

One of the most efficient way to reverse bits of a number is **Xoring**.

Suppose you have a 8 bit number **11010001**. You want to reverse the bits. What is done is that you take **xor** of the number with **11111111**. The result is **00101110**. Internal implementation of xoring is very **efficient** with operation consuming only a **single clock cycle**.

I hope you see how things work out in above example. Similarly, if you have a 32 bit integer, you take xor of the integer with a number whose hex equivalent is **FFFF**.

**Note**: Reversing bits of a signed number **reverses** it sign.

Yes by Xoring individual bits you get the bits reversed no doubt.

Also there’s a container in cpp called ‘BITSET’ which provides some methods for bit operations, you can follow it here.

The inbuilt method that we need here is ‘flip’ here, which takes a bitset and flip all of it’s bits, you can follow the method here.

Also there are even methods to output the contents of a bitset to string or ull etc.

I hope this helps !

If you want to reverse the bits of 32 bit integer just subtract that number from this 4294967295.

If you want to reverse the bits of x then do this x=4294967295-x.Now bits in x will be flipped.

4294967295=2^0+2^1+2^2…+2^31

If you want to reverse the bits of a 64 bit integer then you need to subtract that from 2^0+2^1+…+2^63

Okay i was misunderstanding your question, here’s the output you desire:

```
#include "bits/stdc++.h"
using namespace std;
int main(){
string ip = "00000000000000000000000000000001";
reverse(ip.begin(),ip.end());
std::bitset<32> foo (ip);
cout << foo.to_string() << endl;
cout << foo.to_ulong();
return 0;
}
```

Probably you can take reversed string and calculate it’s value by looping through ?

what is the actual question?

Reverse a 32 bit integer

Do you mean flip bits, or reverse order of bits?

Reverse a 32 bit given number.

00000000000000000000000000000001 =1

10000000000000000000000000000000 =2147483648

Store the required string in the bitset, flip bits, output using the method to_ulong() and you will have desired result here

Refer all the links and you will get it, if not feel free to ask for code !

pseducode.

Okay, working on it

Fixed the format :).

Bro !!

I misunderstood it for flip, it’s reverse bits infact

Flipping of sign is something people forget and tend to waste hours debugging the code. Its really nice to see some so conceptually aware.

Follow it in the below ans by me