<html>
<body>
While reading through the perl-quiz-of-the-week, I noticed this neat test
to find if a number is a power of 2. Originally, I didn't even
believe it worked so I wrote a little program to test it. The
program helped me figure out that it does, in deed, work, and *how* it
works. If a number is a pure powere of 2, it only has one bit
set. If you subtract 1 from it you have to borrow from that bit,
effectively clearing it and setting all the bits below it. If you
then bitwise-and the two numbers, you're guaranteed to come up with
zero. You can't get zero otherwise. Coooool.<br><br>
<br>
<tt>foreach $n (1 .. 2<<8) {<br>
if (( $n & ($n-1)) == 0){<br>
<x-tab> </x-tab>printf
"%4d %10b %10b %10.10b\n" => $n, $n, $n-1,
$n&($n-1);<br>
}<br>
}<br>
$n
$n $n $n &
$n-1<br>
decimal binary
binary binary<br>
1
1 0
0000000000<br>
2
10 1
0000000000<br>
4
100 11 0000000000<br>
8
1000 111 0000000000<br>
16
10000 1111 0000000000<br>
32 100000
11111 0000000000<br>
64 1000000 111111
0000000000<br>
128 10000000 1111111 0000000000<br>
256 100000000 11111111 0000000000<br>
512 1000000000 111111111 0000000000<br><br>
<br>
</tt><x-sigsep><p></x-sigsep>
Michael R. Wolf<br>
All mammals learn by playing!<br>
MichaelRWolf@att.net<br>
</body>
</html>