# Number of bits set in an unsigned char

Is there a rapid way of finding the number of bits set by an unsigned char?

For example,

unsigned char c1=63; //0x3f, binary: 0011 1111
unsigned char c2=67; //0x43, binary: 0100 0011

For c1, the answer I want is 6, and for c2 the answer I want is 3.

I'm going to be doing this calculation A LOT as part of an interative analysis program, and wondered if I should just set up some array like the following. Really would love a super rapid way of evaluating this number.

....
myarray(63) = 6;
....
myarray(67) = 3;
....
myarray(255) = 8;

###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Use

unsigned char countbits ( unsigned char b) {

if ( b & mask) {

count++;
}
}

return ( count);
}
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
Hi,

Instead of calculating number of bits set each time, Create a class and get the result quickly by passing the unsigned char as argument.

Hope the following code might be helpful.

Thanks and Regards,
Ramesh Ramasamy.

Cut and paste the appropriate portion of the code.
//---------------------------------------------------------------------------
#include <stdio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

class MYARRAY {
public:
MYARRAY ();
int operator[](unsigned char n) { return nBits[n]; }
private:
int nBits[256];
};

MYARRAY::MYARRAY() {
int cBits;
for (i = 0; i <= 255; i++) {
if ( i & mask) {
cBits++;
}
}
nBits[i] = cBits;
if (i == 255) break;
}
}

#pragma argsused
int main(int argc, char* argv[])
{
// Create an object
MYARRAY MyArray;

// Get the number of bits set by wrting the following statement.
// MyArray[unsigned char];

// To verify whether no. of bits are set correctly
FILE * fp = fopen ("NoOfBits.txt", "wt");
for (unsigned char i = 0; i <= 255; i++) {
fprintf (fp, "char: %d = %d\n", i, MyArray[i]);
if (i == 255) break;
}

return 0;
}
//---------------------------------------------------------------------------
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.