Home » C programs » C programs on Bitwise Operators

C program to counter number of 1’s in an integer number.

This program will count total number of 1’s in an integer number. Here we are counting total number of 1’s in an integer number using a User Define Function.

Counting number of 1’s using C program

/*C program to count number of 1's in a number */
 
#include <stdio.h>
 
int count1s(unsigned int num)
{
    unsigned char i;
    int count=0;
    
    unsigned char totalBits=sizeof(num)*8;
    
 
    for(i=0;i< totalBits;i++)
    {
        if( num & (1<< i) )
            count++;
    }
 
    return count;
}

int main()
{
    unsigned int data=0x58;
    printf("\nTotal number of 1's are : %d\n",count1s(data));
 
    return 0;
}

Output

    Total number of 1's are : 3




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.