n = 64

IF n >= 0 THEN IF (n AND (n - 1)) = 0 THEN PRINT n; " is a power of 2"

Deceptively simple, isn't it?

How it works:

The AND function looks through all the bits of the two numbers and sets each result bit to one if both of the bits is one. The only way for a number N, and N-1, to not equal each other in ANY bit is right before N-1 turns to N:

10000000 AND 01111111 = 00000000 = 0

Credit: Xhantt, Agamemnus

PowerofTwo - page last edited 2004-01-29 10:26:01 by 172.158.248.117 (home) (edit)

Blast WIKI - by RoboticBoy - edited and tweaked for our evil purposes by Hexadecimal Disaster

Blast WIKI - by RoboticBoy - edited and tweaked for our evil purposes by Hexadecimal Disaster