BIT Manipulations #2 Basics
#include <bits/stdc++.h>
using namespace std;
//get a bit:
int getBit(int n, int i){
//check whether at i, n contains is 0 or 1.
// n = 0101, i = 2
// 1<<i = x --> 1<<2 --> 0100 (at i it makes 1, so using & it ll be beneficial for 1 or 0 prediction.)
// n & x
return (n & (1<<i));
}
//set a bit at i: means place 1 at i in n:
int setBit(int n, int i){
//make 1 no matter.
return (n | (1<<i));
}
//clear bit at i: means place 0 at i in n:
int clearBit(int n, int i){
//make a mask(~ ones complement--> flip 1 by 0 and 0 by 1)
//then mask & n
int mask = ~(1<<i);
return (n & mask);
}
//update a bit at pos with 0 or 1:
int updateBit(int n, int i, int k){
if(k == 1){
//set():
return (n | (1<<i))
}
else{
//clear():
int mask = ~(1<<i);
return (mask & n);
}
}
//how to find n-1 if n is given theortically:
//check if a number is a power of 2 using bit manipulation:
//1. how to find n-1 if n is given in bits? :
/*
n = 1010
flip all bits from right most set bit to rightmost bit. = n-1
n-1 = 1001
*/
// NOTE: if a number is a power of 2 then its binary will contain only single set bit. 0010 1000 000100
// now since every bit is zero except one in n and n-1 we can use & and check if all are = 0.
bool checkPowerof2(int n){
return !(n & (n-1));
}
//get the right most set bit of a number:
int getRightMostSetBiT(int n){
return n & ~(n-1);
}
//get number of set bits by kernighan's algo:
void bitsNum(int n){
int bits = 0;
while(n){
if(n & ~(n-1)) bits++;
n = n - (n & ~(n-1));
}
cout << bits << endl;
}
int main(){
//BIT MANIPULATIONS:
int n;
cin >> n;
int i;
cin >> i;
cout << getBit(n, i) << endl;
cout << clearBit(n, i) << endl;
cout << setBit(n, i) << endl;
return 0;
}
Comments
Post a Comment