forked from Kuwarsaab/git-learn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_bits.cpp
More file actions
41 lines (32 loc) · 939 Bytes
/
reverse_bits.cpp
File metadata and controls
41 lines (32 loc) · 939 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//Given an integer, reverse its bits using binary operators.
#include <iostream>
#include <bitset>
using namespace std;
// A macro that defines the size of an integer
#define INT_SIZE sizeof(int) * 8
// Function to reverse bits of a given integer
int reverseBits(int n)
{
int pos = INT_SIZE - 1; // maintains shift
// store reversed bits of `n`. Initially, all bits are set to 0
int reverse = 0;
// do till all bits are processed
while (pos >= 0 && n)
{
// if the current bit is 1, then set the corresponding bit in the result
if (n & 1)
{
reverse = reverse | (1 << pos);
}
n >>= 1; // drop current bit (divide by 2)
pos--; // decrement shift by 1
}
return reverse;
}
int main()
{
int n = 54;
cout << n << " in binary is " << bitset<32>(n) << endl;
cout << "On reversing bits " << bitset<32>(reverseBits(n));
return 0;
}