Example:
Input any number: 22
Output leading zeros: 27 (using 4 byte signed integer)
Required knowledge:
Basic C programming, Bitwise operator, If else, LoopProgram:
/**
* C program to count leading zeros in a binary number using bitwise operator
*/
#include <stdio.h>
#define INT_SIZE sizeof(int) * 8
int main()
{
int num, count, msb, i;
//Reads a number from user
printf("Enter any number: ");
scanf("%d", &num);
count = 0;
//Equivalent to
//10000000 00000000 00000000 00000000
msb = 1 << (INT_SIZE - 1);
//Iterate over each bit
for(i=0; i<INT_SIZE; i++)
{
//If a leading set bit is found
if((num << i) & msb)
{
//No need to run further
break;
}
count++;
}
printf("Total number of leading zeros in %d is %d", num, count);
return 0;
}
Program: Using another short approach
/**
* C program to count leading zeros in a binary number using bitwise operator
*/
#include <stdio.h>
#include <limits.h> //Used for INT_MAX
int main()
{
int num, count;
//Reads a number from user
printf("Enter any number: ");
scanf("%d", &num);
count = 0;
while(!(num & (~INT_MAX)))
{
count++;
num <<= 1;
}
printf("Total number of leading zeros = %d", count);
return 0;
}
Output
Enter any number: 22
Total number of leading zeros in 22 is 27
Total number of leading zeros in 22 is 27
Note: Output may be different on different compilers since since size of data types are machine dependent.
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to count trailing zeros in a binary number.
- C program to check Least Significant Bit (LSB) of a number is set or not.
- C program to check Most Significant Bit (MSB) of a number is set or not.
- C program to get nth bit of a number.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to toggle nth bit of a number.
- C program to get highest set bit of a number.
- C program to get lowest set bit of a number.
- C program to flip bits of a binary number using bitwise operator.
- C program to total number of zeros and ones in a binary number.
- C program to convert decimal to binary number system using bitwise operator.
- C program to swap two numbers using bitwise operator.
- C program to check whether a number is even or odd using bitwise operator.