-
Notifications
You must be signed in to change notification settings - Fork 13
/
BitManipulation.cpp
65 lines (58 loc) · 1.6 KB
/
BitManipulation.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
#include <bits/stdc++.h>
using namespace std;
int getithBit(int n, int i)
{
int mask = (1 << i - 1);
return (n & mask) == 0 ? 0 : 1;
}
int setithBit(int n, int i)
{
int mask = (1 << i - 1);
return n | mask;
}
int clearithBit(int n, int i)
{
int mask = ~(1 << i - 1);
return n & mask;
}
void updateithBit(int n, int i, int v)
{
// v can be 0 or 1
clearithBit(n, i);
int mask = (v << i - 1);
n = n | mask;
cout << "Updated number is " << n << "\n";
}
int countSetBits(int n)
{
int count = 0;
while (n)
{
count++;
n = n & (n - 1);
}
return count;
}
int clearBitsInRange(int n, int i, int j)
{
int mask1 = (-1 << i);
int mask2 = ~(-1 << j);
int mask = mask1 | mask2;
return n & mask;
}
int main()
{
int n = 10, i = 2, j = 3;
cout << "Bit no. " << i << " from the right for the number " << n << " is " << getithBit(n, i) << "\n";
i = 1;
cout << "Setting bit no. " << i << " from the right for the number " << n << " gives " << setithBit(n, i) << "\n";
cout << "Clearing bit no. " << i << " from the right for the number " << n << " gives " << clearithBit(n, i) << "\n";
updateithBit(n, i, 1);
cout << "Number of set bits in " << n << " is " << countSetBits(n) << "\n";
i = 4;
// example n = 10 i.e. 1010
// i and j are counted from the right-hand side so i or j = 1 means the rightmost bit
// clear bits from 4 to 3 i.e. 1010 -> 0010, so ans = 2
cout << "Clearing bits from " << i << " to " << j << " for the number " << n << " gives " << clearBitsInRange(n, i, j) << "\n";
return 0;
}