SPUG: Cool power-of-2 trick

Brian Hatch bri at ifokr.org
Thu Jan 20 12:29:53 PST 2005

> 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.

This only works on systems where data is stored in binary.  If you're on
a machine that uses ternary storage units (-1 0 +1) then it does not
work for powers of two, but it does work for powers of three.

Of course I'm still waiting for the completely optimal system which uses
storage units of 'e' instead of rounding to 3 for simplicity.

Brian Hatch                  "Would you like to take
   Systems and                a shower with the food?"
   Security Engineer         -- Bree

Every message PGP signed
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.pm.org/pipermail/spug-list/attachments/20050120/b947ed07/attachment.bin

More information about the spug-list mailing list