-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitshift.cpp
115 lines (97 loc) · 2.68 KB
/
bitshift.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <cinttypes>
#include <iostream>
using namespace std;
unsigned int intSetBit(unsigned int target, int bit)
{
unsigned int mask = (1 << bit);
return target | mask;
}
template <class T>
T setBit(T target, int bit)
{
T mask = (1 << bit);
return target | mask;
}
template <class T>
T clearBit(T target, int bit)
{
T mask = (1 << bit);
return target & (~mask);
}
template <class T>
bool testBit(T target, int bit)
{
T mask = (1 << bit);
return target & mask;
}
template <class T>
void printBits(T target)
{
for(int bit = 8 * sizeof(T) -1; bit >=0 ; bit--) {
cout << testBit(target,bit);
}
}
template <class T>
T bit_rol(T t, int bits = 1) // rol = rotate left
{
return (t << bits) | (t >> (8*sizeof(T) - bits));
}
template <class T>
T bit_ror(T t, int bits = 1) // ror = rotate right
{
return (t >> bits) | (t << (8*sizeof(T) - bits));
}
int main(int argc, char ** argv, char ** env)
{
for(int bit = 0; bit < 8; bit++ ) {
unsigned int target = 0;
target = intSetBit(target, bit);
cout <<"intSetBit: bit " << bit << " on, target = " << target << "\n";
}
for(int bit = 0; bit < 8; bit++ ) {
unsigned int target = 0;
target = setBit(target, bit);
cout <<"setBit (template function) bit " << bit << " on, target = " << target << "\n";
}
unsigned short target;
cout << "sizeof(target) = "<< sizeof(target) << " bytes, " << 8 * sizeof(target) << " (bits)" << "\n";
for(int bit = 0; bit < 8*sizeof(target); bit++ ) {
target = ~0;
target = clearBit(target, bit);
// cout <<"clearBit (template function) bit " << bit << " on, target = " << target << "\n";
printBits(target);
cout << "\n";
}
uint8_t A = 23;
uint8_t B = 32;
cout << "A = " << (int) A << "\n";
cout << "B = " << (int) B << "\n";
cout << "A="; printBits(A); cout << "\n";
cout << "B="; printBits(B); cout << "\n";
cout << "\n";
A = A ^ B;
cout << "after A = A ^ B;" << "\n";
cout << "A="; printBits(A); cout << "\n";
cout << "B="; printBits(B); cout << "\n";
cout << "\n";
B = A ^ B;
cout << "after B = A ^ B;" << "\n";
cout << "A="; printBits(A); cout << "\n";
cout << "B="; printBits(B); cout << "\n";
cout << "\n";
A = A ^ B;
cout << "after A = A ^ B;" << "\n";
cout << "A="; printBits(A); cout << "\n";
cout << "B="; printBits(B); cout << "\n";
cout << "\n";
cout << "A = " << (int) A << "\n";
cout << "B = " << (int) B << "\n";
for(int i = 0; i< 256; i++) {
A = i;
cout << "i=" << i << " ";
printBits(A); cout << " ";
printBits(bit_rol(A, 1)); cout << " ";
printBits(bit_ror(A, 1));
cout << "\n";
}
}