Re: test whether a number is a power of 2

From: R. Rajesh Jeba Anbiah (ng4rrjanbiah_at_rediffmail.com)
Date: 10/01/03


Date: 30 Sep 2003 22:00:45 -0700


"jacob navia" <jacob.navia@jacob.remcomp.fr> wrote in message news:<bl7kgo$d5e$1@news-reader5.wanadoo.fr>...
> > isPow2 = x && !( (x-1) & x );
>
> Algorithm:
> If x is a power of two, it doesn't have any bits in common with x-1, since it
> consists of a single bit on. Any positive power of two is a single bit, using
> binary integer representation.
>
> This means that we test if x-1 and x doesn't share bits with the and operator.
>
> Of course, if x is zero (not a power of two) this doesn't hold, so we add an
> explicit test for zero with xx && expression.

        Few Mathematicians say any positive integer raised to the power minus
infinity is 0. That is,
                n (pow) (-infinity) = 0

        IOW, 2 (pow) 3 = 8, 2 (pow) 2 = 4, 2 (pow) 1 = 2, 2 (pow) 0 = 1,
and, 2 (pow) (-infinity) = 0.

        Because of this religious reason, I would just write my macro as
(without 0 check)
                #define ISPOWOF2( n ) ( ! ( n & (n-1) ) )

        But, someone here in CLC told me that the above macro won't work all
the time. I know, it won't work for float; I know the necessity of
additional paranthesis for n. But, I couldn't see any other reasons.
Anybody have any good comments? TIA

---
  "Silence is the only right answer for many wrong questions" --
G.K.Moopanaar, Indian Politician
http://guideme.itgo.com/atozofc/ - "A to Z of C" Project
Email: rrjanbiah-at-Y!com


Relevant Pages

  • Prove that, if x AND x-1 = 0 then x=2^m (m>=0).
    ... x and x-1 (x and x-1 are two numbers stored in computer memory) and we ... get a value zero, then we can say x is a number that is power of 2. ...
    (sci.logic)
  • Re: [OT] Paging Frank K. (was: [OT] Why Bush?)
    ... point is the only people with the power to "lighten up" and "make happy" my ... back of your car and carry on as before, filling up with Uranium rods at ... at all in use when you're being "generic" (and common for non-native ... suggesting before with the notion that things are heading in a certain ...
    (alt.lang.asm)
  • Re: 3 Phase PFC with the Genome Converter
    ... The switching interface is ... much easier too since the switch pair share a common node. ... contrived drive circuits so we can see the power flow. ... I see four AC power leads in your ...
    (sci.electronics.design)
  • Re: Lipstick on Pig
    ... The only AC was the power coming into the units and soon ... made this mistake while wiring your generator to your box. ... The common is ... 120 volt circuit coming out of your breaker box. ...
    (rec.scuba)
  • Re: 3 Phase PFC with the Genome Converter
    ... The switching interface is ... much easier too since the switch pair share a common node. ... Just do the power section with FETs and contrived ... I see four AC power leads in your ...
    (sci.electronics.design)