Code archives/Algorithms/Power of two

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

Download source code

Power of two by Rottbott2005
Updated for a 2x speed increase! (Shl instead of ^.)
; Returns the next power of two down from a positive integer
Function PowerOfTwo(N)

	; Optimise for smaller numbers
	If (N And $FFFF0000) <> 0
		Start = 31
	Else
		Start = 15
	EndIf

	; Find power
	For i = Start To 0 Step -1
		Number = 1 Shl i
		If (N And Number) = Number Then Return Number
	Next

	; N is 0 or less
	Return 0

End Function

Comments

Koriolis2005
Try that
Const CONST_PowerOfTwo_LOG2# = 0.69314718055994530941723212145818
Function PowerOfTwo(N)
;	Return 1 Shl Int(Floor(Log(N)/Log(2)))
	Return 1 Shl Int(Floor(Log(N)/CONST_PowerOfTwo_LOG2))
End Function



Code Archives Forum