This is a C Program to use bitwise operations to count the number of leading zero’s in a number x.

This C Program uses Bitwise operations to count the number of leading zero’s in a number x.

Take input from the user and perform bitwise operations as shown in the program below.

Here is source code of the C Program to use Bitwise operations to count the number of leading zero’s in a number x. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C Program to Use Bitwise Operations to Count the Number of * Leading Zero's in a Number x */ #include <stdio.h> #include <malloc.h> int main() { int lim = sizeof(int) * 8; // the mBit is 1000 0000 0000 0000 0000 0000 0000 0000 int mBit = 1 << (lim - 1); int num = 0, count = 0; printf ("Enter the digit: "); scanf ("%d", &num); while (!(num & mBit)) { num = (num << 1); count ++; } printf ("\nNumber of leading zero's is: %d\n", count); return 0; }

1. Take the input from the user and store it in the num variable. Leading zero’s in a binary number is equal to zeros preceding the highest order set bit of the number.

2. int lim = sizeof(int) * 8; is used to find the total number of bits required to store an integer in memory.

3. For Setting MSG, initialize a variable and set its MSB to 1. We can achieve this by using int mBit = 1 << (lim – 1);. So the mBit will be 10000000 00000000 00000000 00000000. It stores the number of leading zero’s in the variable count.

4. While statement is used to find the leading set bit. If the leading set bit is found we terminate the loop, else right shift the bit by 1 and we increase the value of count by 1.

5. Print the number of leading zero’s in the given number using print statement.

Test case 1 – Here, the entered digit is 16.

gcc leading_zeros.c -o leading-zero ./leading-zero Enter the digit: 16 Number of leading zero's is: 27

Test case 2 – Here, the entered digit is 64.

gcc leading_zeros.c -o leading-zero ./leading-zero Enter the digit: 64 Number of leading zero's is: 25

Test case 3 – Here, the entered digit is 1.

gcc leading_zeros.c -o leading-zero ./leading-zero Enter the digit: 1 Number of leading zero's is: 31

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

**Next Steps:**

- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

**Related Posts:**

- Apply for C Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Buy Computer Science Books
- Practice BCA MCQs