# Power of Two in C

CServer Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have a number n. We have to check whether the number is the power of 2 or not. So is n = 16, then the output will be true, if n = 12, it will be false.

To solve this we will use logical operations. If we see the numbers that are the power of two then in the binary representation of that number will be the MSb is 1, and all other bits are 0. So if we perform [n AND (n – 1)], this will return 0 if n is the power of 2. If we see n = 16 = 10000 in binary, (n – 1) = 15 = 01111 in binary, then 10000 AND 01111 = 00000 = 0

## Example (C)

Let us see the following implementation to get a better understanding −

#include <stdio.h>
#include <math.h>
#define MAX 20
bool isPowerOfTwo(int n){
return(n>0 && !(n & (n-1)));
}
int main() {
printf("%s\n", isPowerOfTwo(16) ? "true" : "false");
printf("%s\n", isPowerOfTwo(12) ? "true" : "false");
printf("%s\n", isPowerOfTwo(1) ? "true" : "false");
printf("%s\n", isPowerOfTwo(32) ? "true" : "false");
printf("\n");
}

## Input

16
12
1
32

## Output

true
false
true
true
Updated on 28-Apr-2020 10:28:29