[SciPy-dev] Testing for powers of two
Charles Harris
charles.harris at sdl.usu.edu
Fri Oct 29 12:12:45 EDT 2004
There was a discussion some time ago about testing for powers of two.
The other day I saw a nifty version go by on the LKML, courtesy of
Linus. Namely:
is_power_of_two = x && !(x & (x - 1))
which works for all numbers except possibly the number x8000, which if
twos complement will probably give an underflow on subtraction of 1. So
for signed numbers:
is_power_of_two = x > 0 && !(x & (x - 1))
Chuck
More information about the SciPy-Dev
mailing list