Bit manipulation  techniques every programmer should know Part - 0

Bit manipulation techniques every programmer should know Part - 0

ยท

3 min read

Bit manipulation

Bit manipulation is the technique of doing some of the basic arithmetic operations using bit-wise operators. It is the fastest way to perform some of the basic operations that we use in our day-to-day programming tasks. We all know that computers store data just as 0s and 1s. Since bit-wise operators directly work on the binary values it is faster than the normal arithmetic operators, but bit manipulation technique can't help us to achieve all our computations. So here I am going to explain some of the basic and most useful tricks. this surely can improve your coding skills and improve the run time of your code.

So let's start with the basics by knowing the bitwise operators and their functionalities.

OIP.jfif


Odd or Even

This is undoubtedly the most common operation you perform every single day as a programmer. When you think about this, what does your mind thinks of?
Let us say, you have a number num and you need to check whether it is an odd or even number.
Every newbie would think of this

if (num % 2 == 0)
    {
        //even
    }
    else
    {
        //odd
    }

using % ( The modulo operator ) and == ( Equality operator ) this is great for a newbie but for a real programmer, this is definitely not.
So what is the better option & ( Bitwise AND operator )

if (num & 1)
    {
        //odd
    }
    else
    {
        //even
    }

Explanation

One important thing to understand here is that for every odd number the bit 1 is always true. As you may know, the bitwise AND operator takes the binary value of both the values and performs bitwise AND, and returns the resulting binary value. So the expression num & 1 returns 1 if the num is odd or 0 if num is even, which is then interpreted by the compiler as true and false respectively.


Multiplying with powers of 2

This is something you would perform in most of the problems if you are attending a contest in Codechef or Codeforces.

Noob approach:

long long pow2(int pow)
{
    // a function to compute powers of 2
    int result = 1, i = 0;
    while (i < pow)
    {
        result *= 2;
        ++i;
    }
    return result;
}

you can use this function to calculate the powers of 2 at any moment then use the same if you need to multiply any number with a given power of 2.

Efficient method:

Finding powers of 2

int result; // to store 2 power 5
result = 1 << 5;

Multiplying with powers of 2

int result; // to store 3 multiplied with 2 power 5
result = 3 << 5;

I hope you like this article please share your views in the comments.
I will post another article about bit manipulation's advanced uses until save time with these 2 tricks.
Thank you โค

ย