Re: test whether a number is a power of 2
From: R. Rajesh Jeba Anbiah (ng4rrjanbiah_at_rediffmail.com)
Date: 10/01/03
- Next message: Robert Stankowic: "Re: Question"
- Previous message: Noah Roberts: "Re: Differences between 'const char' and 'char'"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Robert Stankowic: "Re: Question"
- Previous message: Noah Roberts: "Re: Differences between 'const char' and 'char'"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|