-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbit-operation.cc
75 lines (54 loc) · 1.55 KB
/
bit-operation.cc
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
/*Name: bit operations*/
#include <iostream>
using namespace std;
class BitOperation
{
public:
BitOperation ()
: m_data (0)
{
}
BitOperation (int d)
: m_data (d)
{
}
// method to do this:
// 1, consider the input and output of i-th bit;
// 2, desicde the sequence and operation in this pattern: sequence operation m_data, e.g., 0000 1000 | 0000 0101
// 3, consider the input and output of left bit;
// 4, desicde the sequence and operation in this pattern: sequence operation m_data, e.g., 0000 1000 | 0000 0101
// 5, choose the intersection of above sequences and operations
bool GetBit (const int &i); // get the i-th bit of m_data
int SetBit (const int &i); // set the i-th bit of m_data to 1
int ClearBit (const int &i); // clear the i-th bit of m_data ( set to 0)
private:
int m_data;
};
bool
BitOperation::GetBit (const int &i)
{
return ( (1 << i) & m_data );
}
int
BitOperation::SetBit (const int &i)
{
m_data = (1 << i) | m_data;
return m_data;
}
int
BitOperation::ClearBit (const int &i)
{
m_data = (~(1 << i)) & m_data;
return m_data;
}
int main (int argc, char *argv[])
{
BitOperation op(5);
int i = 1;
cout << " the " << i << "-th bit is " << op.GetBit (i) << endl;
cout << " set the " << i << "-th bit to 1, then we get " << op.SetBit (i) << endl;
cout << " the " << i << "-th bit is " << op.GetBit (i) << endl;
cout << " clear the " << i << "-th bit, then we get " << op.ClearBit (i) << endl;
cout << " the " << i << "-th bit is " << op.GetBit (i) << endl;
return 0;
}