-
Notifications
You must be signed in to change notification settings - Fork 0
/
reversing-bits.cpp
83 lines (81 loc) · 2.07 KB
/
reversing-bits.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<iostream>
#include <bitset>
#include<string>
using namespace std;
unsigned int reverseBitsEvery(unsigned int x, int every) {
unsigned int reversed = 0;
unsigned int everyBits = 0;
int numOfBits = sizeof(x) * 8;
int i,j,k, l;
for (i = 0, j = 0, k = 0, l = 0; i < numOfBits ; i++) {
int temp = (x & (1<<i));
if (j < every) {
if (temp)
everyBits |= (1<<j);
j++;
} else {
// cout << "SAR j " << j << " everyBits " << everyBits <<endl;
for (k = (every - 1); k >= 0; k--, l++) {
if (everyBits & (1<<k))
reversed |= (1<<l);
}
everyBits = 0;
j = 0;
if (temp)
everyBits |= (1<<j);
j++;
}
}
// cout << "SAR j " << j << " everyBits " << everyBits << " l " << l << endl;
for (j = (j-1); j >= 0; j--, l++) {
if (everyBits & (1<<j))
reversed |= (1<<l);
}
return reversed;
}
int main() {
unsigned int x;
cout << "Enter integer : "<< endl;
cin >> x;
// Bitset method to print bitmap
// cout<<bitset<32>(x)<<endl;
cout << "Printing " << x << "'s binary representation : "<<endl;
for (unsigned int i = 1 << 31; i > 0; i = i / 2)
(x & i)? cout <<"1": cout <<"0";
cout<<endl;
cout<<"Attempting to reverse even and odd bits in this bitmap : "<<endl;
unsigned int reverse = 0;
unsigned int sofar[2];
for (unsigned int i = 1 << 31, j = 0, k = 31; i > 0; i = i / 2) {
if (x & i) {
sofar[j] = 1;
} else {
sofar[j] = 0;
}
if (j == 1) {
reverse = reverse | (sofar[j] << k);
reverse = reverse | (sofar[j-1] << (k-1));
j = 0;
k -= 2;
} else {
j++;
}
}
cout << "Reversed bitmap : " << bitset<32>(reverse) << endl;
string str;
cout<<"Attempting to reverse every 2 bits in this bitmap : "<<endl;
for (unsigned int i = 1 << 31; i > 0; i = i / 2) {
str = ((x & i)?"1":"0") + str;
if (str.size()==2) {
cout<<str;
str.clear();
}
}
cout<<endl;
cout<<"Attempting to reverse every 2 bits inside integer datatype : "<<endl;
unsigned int reverseX = reverseBitsEvery(x, 2);
for (unsigned int i = 1 << 31; i > 0; i = i / 2)
(reverseX & i)? cout <<"1": cout <<"0";
cout<<endl;
return 0;
}