C Programming Code Examples C > Bitwise Operators Code Examples C program to count leading zeros in a binary number C program to count leading zeros in a binary number Write a C program to input any number from user and find total number of leading zeros of the given number. How to find total leading zeros of a given number (in binary representation) using bitwise operator in C programming. Input number from user. Store it in some variable say, j. Find total bits required to store an integer in memory say, INT_SIZE = sizeof(int) * 8. Initialize a variable and set its MSB to 1, say msb = 1 << (INT_SIZE - 1);. Initialize a variable to store leading zeros count, say count = 0;. Run a loop from 0 to INT_SIZE. The loop structure should look like for(i=0; i<INT_SIZE; i++). Inside the loop, left shift j, i times and check its MSB is set or not. If its MSB is set i.e. if((j << i) & msb) then terminate the loop; otherwise increment count by 1. /* 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 j, count, msb, i; /* Input number from user */ printf("Enter any number: "); scanf("%d", &j); // Equivalent to // 10000000 00000000 00000000 00000000 msb = 1 << (INT_SIZE - 1); count = 0; /* Iterate over each bit */ for(i=0; i<INT_SIZE; i++) { /* If leading set bit is found */ if((j << i) & msb) { /* Terminate the loop */ break; } count++; } printf("Total number of leading zeros in %d is %d", j, count); return 0; }