Problem : Check whether given number is power of 2 using bitwise operators in C
Algorithm :
Let us see the binary representation of numbers which are power of 2:
2 - 10
4 - 100
8 - 1000
16 - 10000
32 - 100000
As we can see in above example,any number which is power of 2 has only 1 bit set. Now let us subtract 1 from above power of 2 numbers.
1 - 01
3 - 011
7 - 0111
15 - 01111
31 - 011111
Now we see that when we subtract by 1, we get all 1’s expect for which was originally set for power of 2.
So when we do bitwise-AND between a number which is power of 2 and number which is power of 2 minus 1, we will get 0.
// C program to check whether the given number is power of 2 using bitwise operators
#include <stdio.h>
#include <stdbool.h> //for bool
/*Function which returns true if given number is power of 2*/
bool power_of_2(int number)
{
/*If the number is 1, directly return false*/
if(number == 1)
return false;
/*Check whether the number is power of 2*/
if((number & (number - 1)) != 0)
return false;
/*return true when number is power of 2*/
return true;
}
int main() {
int number = 0;
bool result = false;
printf("\r\nEnter a number:");
scanf("%d", &number);
result = power_of_2(number);
if(result == true)
printf("\r\n%d is Power of 2\n", number);
else
printf("\r\n%d is NOT Power of 2\n", number);
return 0;
}
You can check more about power of 2 here : https://en.wikipedia.org/wiki/Power_of_two