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 (in binary representation) using bitwise operator. How to find total number of leading zeros of a given number (in binary representation) using bitwise operator in C programming. Finding total number of leading zeros of a given number using C programming.

Example

Input

Input any number: 22

Output

Output leading zeros: 27 (using 4 byte signed integer)

Required knowledge

Basic C programming, Bitwise operator, If else, Loop

Leading zeros in a binary number

Program to count leading zeros in a binary number

/**
 * 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;

    // Input 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;
}

Below is another short and effective approach to solve the program.

Program to count leading zeros in a binary number 2

/**
 * 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;

    // Input 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

Note: Output may be different on different compilers since since size of data types are machine dependent.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>