Harald van D?k wrote:
>
> CBFalconer wrote:
> > Harald van D?k wrote:
> > > wrote:
> > >
> > >> On 32-bit platform, I am working on getting how many bits equal
> > >> to 1 without an if loop.
> > >
> > > Use a for loop or a while loop, testing each bit until you have
> > > no more bits to test. I'm not sure what an if loop would be like,
> > > unless you're using goto.
> >
> > I have no idea what an 'if loop' is.
> > [example]
> > which doesn't care how wide an int is.
>
> And the way I mentioned does?
>
> count = value < 0;
> for (bit = 1; bit < INT_MAX / 2; bit *= 2)
> if (value & bit)
> count++;
>
> It accepts ints of any width.
But it needs to know the precise type. My version will work when
fed bytes, longs, shorts, etc. (with matching changes in the type
of value, but making value an unsigned long will cover them all,
except long long which may or may not be available).
I find code fragments that need no editing more useful.
--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews