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 any number: 22
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:

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

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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment