compliement oprator in cpp code example

Example 1: bit manupulation in c++

Bitwise Operator
//if both are true then true else false
&
//if both are false then false else true
|
//changes true into false and vice-versa
~
//returns true if exactly one is true else false
//checks if both are different
^
//a<<b multiply a with 2 , b times
<<
//a>>b divide a with 2 ,  b times
>>
-------------------------------------------------
check whether a numbe is a power of 2
i.e if it comes in the format 2**n
int x;
cin >>x;
cout<<~(x&(x-1));
-------------------------------------------------
count no of ones in the binary representation of th given number
int count = 1;
while(n!=0){
    count++;
    n = n&(n-1);
}
-------------------------------------------------
check whether the i'th bit is set or not i.e 1
for the binary of number n
if(n & (1<<i) == true){
    cout<<"Yes it is a bit"
}
-------------------------------------------------

Example 2: bitwise operator

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25
  00001100
& 00011001
  ________
  00001000  = 8 (In decimal)

Tags:

Cpp Example