'Bit'actics

'Bit'actics

Bit Magic

·

3 min read

Let's look at some of the useful tactics of the Bitwise Operators

bit-_thebit.fit_lim.size_1000x.jpg Divide a number by 2

n=n>>1;

Multiply a number by 2

n=n<<1;

Count total bits in a number

// if n =5 and binary representation is 101
//TotalBits=3
TotalBits = log2(n)+1;

Swapping Two Numbers

x^= y;
y^= x; 
x^= y;

How to set a bit in the number num

//first we set a bit at nth postion
x=1<<n;
//Then perforn OR opeartion to set the bit
res=x|num;

How to unset a bit in the number num:

//first we set the bit at the nth position
x=1<<n;
//Then use NOT operator to unset the nth bit and set remaining bits
x=~x;
//at last, perform the AND operation to unset the desired bit 
res=x&num;

Checking if the bit at nth position is set or unset

x=1<<n;
if(x&1==1)
  cout<<"Bit is set";
else 
  cout<<"Bit is unset";

Count set bits in an number n

count=0;  
while (n)
 {
            n &= (n - 1);
            count++;
  }
//Time Complexity:O(logn)

To check whether a given number is the power of 2 or not

if(n&(n-1)==0)
cout<<"TRUE";
else
cout<<"FALSE;

The Most significant set bit in the given number

//calculating logarithm base 2 of the given number, i.e., log2(N) gives the position of the MSB in N.
//Once, we know the position of the MSB, calculate the value corresponding to it by raising 2 by the power of the calculated position. That is, value = 2log2(N).

To check the given number is Even or Odd

if(n&1==1)
cout<<"Odd Number";
else
cout<<"Even Number";

Never let yesterday use up too much of today. - Will Rogers

Do leave your feedback and suggestions👀.