RE: [AVR-Chat] Exclusive or
2004-06-20 by Paul Curtis
Hi,
> The following comninations will also yield a 1:
>
> 0111
> 1011
> 1101
> 1110
>
> I think that David made a mistake on his 0111 entry.
>
> To check that only one bit is set is the same thing as saying
> that a number is a power of two.
>
> If the expression ( x & ( x - 1 )) yields zero, then x is a
> power of two.
To be completely pedantic, that isn't quite true when x==0 as zero is
not a power of two.
What you could also point out is that x & (x-1) removes the rightmost 1
bit of x and can easily be used to accelerate a "bit count" subroutine:
unsigned bitcnt(unsigned x)
{
unsigned n;
if (x == 0)
return 0;
n = 1;
while ((x &= x-1) != 0)
++n;
return n;
}
--
Paul Curtis, Rowley Associates Ltd http://www.rowley.co.uk
CrossWorks for MSP430, ARM, and (soon) Atmel AVR processors