Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
Count Set Bits in an Integer (C Program)
๐ข Count Set Bits in an Integer (C Program)
#include<stdio.h>
int count_set_bits(int num)
{
unsigned int mask = (unsigned int)num;
int count = 0;
while(mask)
{
count += mask & 1;
mask >>= 1;
}
return count;
}
int main( )
{
int number;
// printf("Enter the number: ");
scanf("%d", &number);
int result = count_set_bits(number);
printf("The count of set bits is %d\\n", result);
}
๐ Explanation:
This program counts the number of set bits (1s) in the binary representation of an integer using bitwise operations.
๐น `mask & 1` checks the least significant bit (LSB) of the number.
๐น If it's 1, `count` is incremented.
๐น The mask is then right-shifted using `mask >>= 1` to check the next bit.
๐น The loop continues until the entire binary number is processed.
๐ธ Note: Casting `num` to `unsigned int` ensures correct behavior for negative numbers (avoiding sign extension).
๐ Sample Output:
Input:
13
Output:
The count of set bits is 3
๐ท️ Keywords:
count set bits C, number of 1s in binary, bitwise AND, C bit manipulation, right shift, count bits using loop
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment