C Program to count trailing and leading zeros in a binary number

CServer Side ProgrammingProgramming

To begin with, let us understand what are trailing zeros in a binary number.

Trailing zeros

The position of zeros after first one from the least significant bit (LSB) is called as trailing zeros in binary number.

Example

104 is decimal number

Binary number of 104 is: (MSB) 1101000(LSB)

Here,

  • MSB refers to Most Significant Bit.
  • LSB refers to Least Significant Bit.
  • From LSB after the first bit set, there are three zero.
  • The number of trailing zeros is three.

Example

Following is the program to count number of trailing zeros for a given number −

 Live Demo

#include<stdio.h>
#include<stdlib.h>
int main(){
   int number, i, trail = 0, size;
   printf("Enter a number\n");
   scanf("%d",&number);
   size = sizeof(number) * 8;
   for(i = 0; i < size; i++){
      if((number >> i) & 1) {
         break;
      }
      trail++;
   }
   printf("Number of trailing ZERO is = %d", trail);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Enter a number
24
Number of trailing ZERO is = 3

Leading zeros

If the position of zero before bit is set to one, they are termed as leading zeros.

Example

94 is decimal number.

Binary number of 94 is: (MSB) .....001011110(LSB)

Number of Leading ZERO is = 25

Program

Given below is the program to count number of leading zeros for a given number.

 Live Demo

#include<stdio.h>
#include<stdlib.h>
int main(){
   int number, i, lead = 0, Msb,size;
   printf("Enter a number\n");
   scanf("%d",&number);
   size = sizeof(number) * 8;
   Msb=1<<(size-1);
   for(i = 0; i < size; i++){
      if((number << i) & Msb) {
         break;
      }
      lead++;
   }
   printf("Number of Leading ZERO is = %d", lead);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Enter a number
94
Number of Leading ZERO is = 25
raja
Published on 12-Mar-2021 11:07:39
Advertisements