for an application I'm working on, I needed a somewhat quick method to find the next power of two value equal to or larger than any integer value I might have. I cooked something up that I might as well drop here, enjoy!
If there is a faster method to do this, I'd like to hear about it...

I tested this code on Win11/X64 using Purebasic 6.21
Code: Select all
; NextPowerOfTwo.pb - calculates next power of two integer bigger than x.i
Procedure.i NextPowerOfTwo(x.i)
If x <= 0 Or x > 2147483648 ; valid input range 1..2^31 for x64 integers
Debug "NextPowerOfTwo() ERROR: Invalid input value - " + Str(x)
ProcedureReturn 0
Else
x - 1 ; ensures x.i itself is returned if already power of two,
x | x >> 1 ; sets all bits to the right to 1 ...
x | x >> 2
x | x >> 4
x | x >> 8
x | x >> 16
x + 1 ; ... then adds one to get the next power of two value.
ProcedureReturn x
EndIf
EndProcedure
; Test driver
Procedure TestNextPowerOfTwo()
Dim testValues.i(10)
Define i.i
Define result.i
testValues(0) = 0
testValues(1) = 2
testValues(2) = 3
testValues(3) = 15
testValues(4) = 16
testValues(5) = 31
testValues(6) = 999999999999999
testValues(7) = 65536
testValues(8) = 6553500
testValues(9) = 84
For i = 0 To ArraySize(testValues()) - 1
Result = NextPowerOfTwo(testValues(i))
If Result > 0
Debug "Input: " + Str(testValues(i)) + " => Next Power of Two: " + Str(result)
EndIf
Next
EndProcedure
TestNextPowerOfTwo()