Code archives/Algorithms/IsPow2 - Power of two test

This code has been declared by its author to be Public Domain code.

Download source code

IsPow2 - Power of two test by BlitzSupport2014
Was just trying this algorithm out in passing!
' http://yarchive.net/comp/power_of_two.html

Function IsPow2:Int (value:Int)
	Return Not (value & (value - 1))
End Function

' For > Int values! Both versions can be passed Ints or Longs
' in the demo, though what happens when you exceed the supported
' range is... "unsupported".

Function IsPow2Long:Long (value:Long)
	Return Not (value & (value - 1))
End Function

Print ""
Print "Ints..."
Print ""

For Local loop:Int = 0 To 128
	Print loop + " : " + IsPow2 (loop)
Next

Print ""
Print "Longs..."
Print ""

For Local longloop:Long = 0 To 128
	Print longloop + " : " + IsPow2Long (longloop)
Next

Comments

Floyd2014
This is fine for positive numbers, which is probably how it would get used.

It fails for 0, which is not a power of two. There is no integer n with 0 = 2^n.

It also fails for the two values with a single 1 bit in the leftmost ( sign ) position i.e. 1:Int Shl 31 and 1:Long Shl 63.
Those would be powers of two if the values were unsigned.

If you want to allow non-positive values then add a test to the return value:

	Return ( value > 0 ) And Not (value & (value - 1))



Code Archives Forum