pranay_teja
10/4/2018 - 6:24 AM

Basic Bit operations on ith Bit

#include<bits/stdc++.h>
using namespace std;

// https://www.youtube.com/watch?v=NLKQEOgBAnw
/* Test Case:
	00101100
	5th bit from right=1
	00100000
	11011111
*/

int get_ith_bit(long x,int i);
void set_ith_bit(long &x,int i);
void clear_ith_bit(long &x,int i);

int main(){
	long bin;
	cin>>bin;
	int i;
	cin>>i;	// ith bit
	cout<<get_ith_bit(bin,i)<<endl;
	cin>>i;
	clear_ith_bit(bin,i);
	cout<<bin<<endl;
	cin>>i;
	set_ith_bit(bin,i);
	cout<<bin<<endl;
	return 0;
}

int get_ith_bit(long x,int i){
	long y=1;
	y=y<<i;
	if(x&y==0){
		return 0;
	}else{
		return 1;
	}
}
void set_ith_bit(long &x,int i){
	long y=1;
	y=y<<i;
	x=x|y;
}
void clear_ith_bit(long &x,int i){
	long y=1;
	y=y<<i;
	y=(~y);
	x=x&y;
}