November 28, 2020, 10:45:17 AM

### Author Topic: [bmx] Round to power of two by Otus [ 1+ years ago ]  (Read 1345 times)

#### BlitzBot

• Jr. Member
• Posts: 1
##### [bmx] Round to power of two by Otus [ 1+ years ago ]
« on: June 29, 2017, 12:28:43 AM »
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[/url].

Code :
Code: BlitzMax
1. Print Round(7) + "=" + 8.0
2. Print Round(1.0/17) + "=" + (1.0/16)
3. Print Round(1 Shl 9 + 1 Shl 7)+ "=" + Float(1 Shl 9)
4. Print Round(1 Shl 9 + 1 Shl 8)+ "=" + Float(1 Shl 10)
5.
6. Function Round:Float(f:Float)
7.         Const MASK_EXPONENT:Int = %11111111 Shl 23
8.         Const MASK_NOMANTISSA:Int = %111111111 Shl 23
9.         Const MASK_MANTISSA_FIRST:Int = 1 Shl 22
10.         Const MASK_EXPONENT_LAST:Int = 1 Shl 23
11.
12.         Local i:Int = Int Ptr( Varptr f )[0]
13.
14.         If 0 > (i & MASK_EXPONENT) Or (i & MASK_EXPONENT) = MASK_EXPONENT
15.                 ' Zero, infinity, NaN...
16.                 Return f
17.         End If
18.
20.                 ' Round up
21.                 i = (i & MASK_NOMANTISSA) + MASK_EXPONENT_LAST
22.         Else
23.                 ' Round down
24.                 i = (i & MASK_NOMANTISSA)
25.         End If
26.
27.         Return Float Ptr( Varptr i )[0]
28. End Function