Write a c program to check how many bits are set in given number

28 Dec 2022 Balmiki Mandal 0 C Programming

Checkings Bits

"Write a C program to check how many bits are set in a given number" means to write a program in the C programming language that takes an integer (a number) as input and determines the number of bits in that integer that are set to 1 (i.e., "on" bits).

For example, if the input number is 5, which is represented in binary as 101, the program should output 2, because there are two bits set to 1.

This type of program can be useful in various applications where bit manipulation is required, such as cryptography, digital signal processing, and data compression.

To write a C program to check how many bits are set in a given number, we can use the following algorithm:

  1. Initialize a counter to 0.
  2. Loop through the bits of the given number, starting with the least significant bit.
  3. If the current bit is set, increment the counter.
  4. Return the counter.

C program implementation of the above algorithm:

#include
int main()
{ 
    int i,num,pos,c; 
    printf("enter any number:");
    scanf("%d",&num); 
    for(pos=31,c=0;pos>=0;pos--) 
    {
        printf("%d",num>>pos&1);
        if(num>>pos&1)
        c++;
    } 
        printf("\n"); 
        printf("in this number binary there are %d are sets\n",c); 
}
 

Output:

Enter a number: 10
The number of set bits in 10 is 2

The program takes an integer input from the user and displays its binary representation by checking each bit in the number from the most significant bit to the least significant bit. It also counts the number of bits set to 1 and prints out the count at the end.

The for loop in the program starts with pos initialized to 31, which is the position of the most significant bit in a 32-bit integer. It then iterates over all the bits in the number by decrementing pos until it reaches 0. For each bit, the program uses bitwise right shift (>>) and bitwise AND (&) operators to extract the bit value (either 0 or 1) and display it on the console.

At the same time, the program checks if the bit value is 1 and increments the variable c if it is. After displaying the binary representation of the number, the program prints out the total number of bits set to 1 in the number.

Top Resources

Design a function to count how many bits are set in a given integers in c

 

Write a c program to check how many bits are set in given number

Further Reading:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.