shekar b.c wrote:
> Hi all
>
> Give a very good method to count the number of ones in a 32 bit
> number. (caution: looping through testing each bit is not a solution).
>
> regards
A fast way to do it is like this (warning, I don't have time to compile
and run it, there might be little errors):
int nrBits[256];
void Fill_nrBits()
{
for (int i=0; i<256; ++i)
{
int countBits=0;
int n=i;
for (int bit=0; bit<8; ++bit)
{
if ((n&1)==1)
++countBits;
n >>= 1;
}
nrBits[i] = countBits;
}
}
int GetNrBits(int n)
{
unsigned char *c = (unsigned char*)&n;
return nrBits[c[0]] + nrBits[c[1]] + nrBits[c[2]] + nrBits[c[3]];
}
int main()
{
Fill_nrBits();
int n = 12345;
int m = GetNrBits(n);
}
--
Mark Van Peteghem
http://www.q-mentum.com -- easier and more powerful unit testing
------------------------ Yahoo! Groups Sponsor --------------------~-->
$9.95 domain names from Yahoo!. Register anything.
http://us.click.yahoo.com/J8kdrA/y20IAA/yQLSAA/EbFolB/TM
--------------------------------------------------------------------~->
To unsubscribe : [EMAIL PROTECTED]
Yahoo! Groups Links
<*> To reply to this message, go to:
http://groups.yahoo.com/group/Programmers-Town/post?act=reply&messageNum=3659
Please do not reply to this message via email. More information here:
http://help.yahoo.com/help/us/groups/messages/messages-23.html
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/Programmers-Town/
<*> To unsubscribe from this group, send an email to:
[EMAIL PROTECTED]
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/