In <(E-Mail Removed)>

(E-Mail Removed) (Aishwarya) writes:

>Joona I Palaste <(E-Mail Removed)> wrote in message news:<bl79og$2tv$(E-Mail Removed)>...

>> Matt <(E-Mail Removed)> scribbled the following:

>> > Give a one-line C expression to test whether a number is a power of 2.

>> > No loops allowed.

>>

>> ((((x&&!(x&(x-!!x)))+x)-x)^x)^x

>

>i know this works because i just tested it .. but help me understand

>the algoritm please ..
Had you engaged your brain, you'd have easily noticed that one ^x cancels

the other and that -x cancels the +x, so you're left with

x&&!(x&(x-!!x))

Now, !!x is an obfuscated way of writing 1, when you know that x cannot

be zero (it was already tested), so, we're left with:

x&&!(x&(x-1))

The tricky bit is x&(x-1) which actually clears the least significant

bit that happens to be set. If the original number was a power of two,

it had only one bit set, so the result of x&(x-1) must be zero in such

cases.

The rest should be obvious.

Dan

--

Dan Pop

DESY Zeuthen, RZ group

Email:

(E-Mail Removed)