SPUG: Cool power-of-2 trick

Michael R. Wolf MichaelRWolf at att.net
Thu Jan 20 14:08:05 PST 2005


At 01:30 PM 1/20/2005, Michael R. Wolf wrote:
>At 12:29 PM 1/20/2005, Brian Hatch wrote:
>
>
>> > 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.


What does a trinary trit-wise &-operator act like?  What's the boolean(?) 
value of each of the trit states?  What's the semantic meaning of the 
lowest-level '&' operator in that context?

Here's a binary table for the results of the &-operator:

  & | 0  1
  --+-----
  0 | 0  0
  1 | 0  1

Analagous to this boolean truth table

  & | F  T
  --+-----
  F | F  F
  T | F  T


What's the trinary logic table?

  & | -1  0  1
  --+---------
-1 |  x  x  x
  0 |  x  x  x
  1 |  x  x  x

What's Boole have to say about its analog?

  & | -1  0  1
  --+---------
-1 |  x  x  x
  0 |  x  x  x
  1 |  x  x  x


Michael R. Wolf
     All mammals learn by playing!
         MichaelRWolf at att.net



More information about the spug-list mailing list