×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to count the number of leading zeros in a binary number

Here, we are going to learn how to count the number of leading zeros in a binary number in C programming language?
Submitted by Nidhi, on July 31, 2021

Problem statement

Read an integer number from the user, find the leading zeros in the input binary number using C program.

C program to count the number of leading zeros in a binary number

The source code to count the number of leading zeros in a binary number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to count the number of leading zeros
// in a binary number

#include <stdio.h>
#include <malloc.h>

int main()
{
    int num = 0;
    int cnt = 31;

    printf("Enter the digit: ");
    scanf("%d", &num);

    printf("Binary number: ");
    while (cnt >= 0) {
        if (num & (1 << cnt))
            printf("1");
        else
            printf("0");
        cnt--;
    }

    cnt = 0;
    while (!(num & (1 << 31))) {
        num = (num << 1);
        cnt++;
    }

    printf("\nNumber of leading zero's are: %d\n", cnt);

    return 0;
}

Output

RUN 1:
Enter the digit: 8
Binary number: 00000000000000000000000000001000
Number of leading zero's are: 28

RUN2:
nter the digit: 65535
Binary number: 00000000000000001111111111111111
Number of leading zero's are: 16

RUN 3:
Enter the digit: 1
Binary number: 00000000000000000000000000000001
Number of leading zero's are: 31

Explanation

Here, we read an integer number and print the corresponding binary number. Then we count the leading zeros in binary numbers and printed the result on the console screen.

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.