Home »
C programs »
C bitwise operators programs
C program to find the next number power of 2
Here, we are going to learn how to find the next number power of 2 in C programming language?
Submitted by Nidhi, on July 24, 2021
Problem statement
Read an integer number from the user, then find the next number power of 2 using the bitwise right shift operator using C program.
C program to find the next number power of 2
The source code to find the next number power of 2 is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to find the next number power of 2
#include <stdio.h>
#include <math.h>
int main()
{
int num = 0;
int i = 0;
printf("Enter Number: ");
scanf("%d", &num);
num--;
while (i <= 4) {
num = num | (num >> (int)pow(2, i));
i++;
}
num++;
printf("The next number, power of 2 is: %d\n", num);
return 0;
}
Output
RUN 1:
Enter Number: 18
The next number, power of 2 is: 32
RUN 2:
Enter Number: 3
The next number, power of 2 is: 4
RUN 3:
Enter Number: 123
The next number, power of 2 is: 128
Explanation
In the main() function, we read an integer number from the user and then found the next number, power of 2 using the bitwise right shift (>>) operator and printed the result on the console screen.
C Bitwise Operators Programs »