Bit Manipulation

Check ith Bit

#include <iostream> using namespace std; int main() { int n=2; int i=3; int mask=1<<(i-1); if(mask & n) cout<<"Set"; else cout<<"Not Set"; return 0; }

Setting ith bit

#include <bits/stdc++.h> using namespace std; int main() { int n=9; bitset<32>b(9); cout<<b<<"\n"; int i=3; int mask=1<<(i-1); cout<<(mask | n); }

Clearing ith bit

#include <bits/stdc++.h> using namespace std; int main(){ int i=1; int mask=1<<(i-1); mask=~mask; int n=81; cout<<(mask & n)<<"\n"; return 0; }

Remove last set bit of a number

#include <bits/stdc++.h> using namespace std; int main(){ int n=81; cout<<((n-1)& n)<<"\n"; return 0; }

Find the position of rightmost setbit

#include <bits/stdc++.h> using namespace std; int main(){ int n=8; bitset<32>b1(n); cout<<b1<<"\n"; bitset<32>b2(-n); cout<<b2<<"\n"; cout<<(int)log2(n&(-n))+1<<"\n"; return 0; }

Odd or Even

#include <bits/stdc++.h> using namespace std; int main(){ int n=8; if(n&1) cout<<"Odd\n"; else cout<<"Even\n"; return 0; }

Power Of Two

#include <iostream> #include <bitset> using namespace std; int main() { int n = 8; bitset<32> b(n-1); cout << b << "\n"; bitset<32> b1(n); cout << b1 << "\n"; cout << (b & b1) << "\n"; bitset<32> c(0); if ((b & b1) == c) cout << "Yes\n"; else cout << "No\n"; return 0; }

Power Of Four