Skip to content

Instantly share code, notes, and snippets.

@cscheid
Created September 10, 2014 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cscheid/240a35e313875feb44a5 to your computer and use it in GitHub Desktop.
Save cscheid/240a35e313875feb44a5 to your computer and use it in GitHub Desktop.
A monotonic transformation from IEEE 754 floats to unsigned ints

You need to get to the bit representation of the float, and then:

inline unsigned int float2fint(unsigned int f) {
    return f ^ ((-(f >> 31)) | 0x80000000);
}

Callahan et al. used this trick in this paper.

Caveats:

  1. 32-bit float only. I'm sure there are generalizations for doubles, etc.
  2. No idea what it does to NaN's (although I've a vague recollection that this does the right thing to denormals. I could be wrong)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment