×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to count 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

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.