-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitwise_Operations.cpp
More file actions
95 lines (78 loc) · 2.12 KB
/
Bitwise_Operations.cpp
File metadata and controls
95 lines (78 loc) · 2.12 KB
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
#include <bits/stdc++.h>
using namespace std;
// Return the kth bit of x
int kth_bit(int x, int k) {
return x >> k & 1;
}
// Set the kth bit of x
int set_kth_bit(int x, int k) {
return x | (1 << k);
}
// Unset the kth bit of x
int unset_kth_bit(int x, int k) {
return x & (~(1 << k));
}
// Toggle the kth bit of x
int toggle_kth_bit(int x, int k) {
return x ^ (1 << k);
}
// Return the lowest set bit of x
int lowest_set_bit(int x) {
return x & -x;
}
// Unset the lowest set bit of x
int unset_lowest_set_bit(int x) {
return x & (x - 1);
}
// Check x is odd
bool is_odd(int x) {
return x & 1;
}
// Check x is a power of 2
bool check_power_of_2(int x) {
return __popcount(x) == 1;
}
// Print the binary representation of x
void print_binary(int x) {
for (int k = 31; k >= 0; k--) {
cout << (x >> k & 1);
}
cout << '\n';
}
void solve() {
int n;
cin >> n;
print_binary(n);
// Builtin function in GCC
// __builtin_popcountll, __builtin_ffsll, __builtin_clzll, __builtin_ctzll
// Count of set bits
cout << "popcount: " << __builtin_popcount(n) << '\n';
// Index of the lowest set bit
cout << "ffs: " << __builtin_ffs(n) << '\n';
// Count of leading zeros
cout << "clz: " << __builtin_clz(n) << '\n';
// Count of trailing zeros
cout << "ctz: " << __builtin_ctz(n) << '\n';
// Count of set bits
cout << "popcount: " << __popcount(n) << '\n';
// Return bit lenght of n
cout << "bit_width: " << __bit_width(n) << '\n';
// Round down/up to the next power of two
cout << "Round: " << __bit_floor(n) << ' ' << __bit_ceil(n) << '\n';
// Rotate left/right
cout << "Rotate: " << __rotl(n, 4) << ' ' << __rotr(n, 4) << '\n';
// Count of leading/trailing zeros
cout << "Count Zeros: " << __countl_zero(n) << ' ' << __countr_zero(n) << '\n';
// Count of leading/trailing ones
cout << "Count Ones: " << __countl_one(n) << ' ' << __countr_one(n) << '\n';
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}