Hi,
> > Indeed!
> >
> > I don't see a lot of this sort of thing anymore, here, or
> on the piclist.
> > Used to be, several years ago..
> >
>
> OK - how about another classic problem. Again, fine when you
> know but worth looking for a solution. Efficient code for
> counting the ones in an
> 8 or 16 bit value - say for a majority vote or some such.
>
> Pete Harrison
unsigned count_ones(unsigned x)
{
unsigned ones;
for (ones = 0; x; x &= x-1)
++ones;
return ones;
}
By extension you can say "does some value x have at least 2 one bits?"
easily:
// non-zero if at least two bits are set in x.
unsigned
at_least_two_1_bits_set_p(unsigned x)
{
return x == 0 ? 0 : x & (x-1);
}
--
Paul Curtis, Rowley Associates Ltd http://www.rowley.co.uk
CrossWorks for MSP430, ARM, AVR and (soon) MAXQ processorsMessage
RE: [AVR-Chat] Re: Challenge
2005-06-09 by Paul Curtis
Attachments
- No local attachments were found for this message.