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