[bmx] Round to power of two by Otus [ 1+ years ago ]

Started by BlitzBot, June 29, 2017, 00:28:43

Previous topic - Next topic

BlitzBot

Title : Round to power of two
Author : Otus
Posted : 1+ years ago

Description : Rounds a float to the closest power of two, which is required in some algorithms. Quite low level, see <a href="http://en.wikipedia.org/wiki/Single_precision" target="_blank">IEEE Float</a>.

Code :
Code (blitzmax) Select
Print Round(7) + "=" + 8.0
Print Round(1.0/17) + "=" + (1.0/16)
Print Round(1 Shl 9 + 1 Shl 7)+ "=" + Float(1 Shl 9)
Print Round(1 Shl 9 + 1 Shl 8)+ "=" + Float(1 Shl 10)

Function Round:Float(f:Float)
Const MASK_EXPONENT:Int = %11111111 Shl 23
Const MASK_NOMANTISSA:Int = %111111111 Shl 23
Const MASK_MANTISSA_FIRST:Int = 1 Shl 22
Const MASK_EXPONENT_LAST:Int = 1 Shl 23

Local i:Int = Int Ptr( Varptr f )[0]

If 0 > (i & MASK_EXPONENT) Or (i & MASK_EXPONENT) = MASK_EXPONENT
' Zero, infinity, NaN...
Return f
End If

If i&MASK_MANTISSA_FIRST
' Round up
i = (i & MASK_NOMANTISSA) + MASK_EXPONENT_LAST
Else
' Round down
i = (i & MASK_NOMANTISSA)
End If

Return Float Ptr( Varptr i )[0]
End Function


Comments : none...