Skip to content

Instantly share code, notes, and snippets.

@dockimbel
Created June 12, 2012 20:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dockimbel/2919931 to your computer and use it in GitHub Desktop.
Save dockimbel/2919931 to your computer and use it in GitHub Desktop.
Float32! to integer! conversion routine
Red/System [
Title: "Float32! to integer! conversion routine"
Author: "Nenad Rakocevic"
Rights: "Copyright (C) 2011 Nenad Rakocevic. All rights reserved."
License: "BSD-3 - https://github.com/dockimbel/Red/blob/origin/BSD-3-License.txt"
Note: "Thanks to François Jouen for providing me the C code for ftoi()"
]
float-to-integer: func [
f [float32!] ;-- float 32-bit value to convert
return: [integer!] ;-- truncated integer value returned
/local dw exp value
][
dw: as-integer f
if zero? dw [return 0]
exp: ((dw >>> 23) and FFh) - 127
if any [negative? exp exp > 23][return 0]
value: (1 << exp) + ((dw and 007FFFFFh) >> (23 - exp))
either negative? dw [negate value][value]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment