Skip to content

Instantly share code, notes, and snippets.

@orlp

orlp/fast_ftol.c Secret

Created April 30, 2012 12:17
Show Gist options
  • Save orlp/f29a0a7813df398fc494 to your computer and use it in GitHub Desktop.
Save orlp/f29a0a7813df398fc494 to your computer and use it in GitHub Desktop.
#include <stdint.h>
int fast_ftol(float x) {
union {
float f;
uint32_t i;
} float_conv;
uint32_t mantissa;
int exponent;
int result;
/* load float in union */
float_conv.f = x;
/* extract the mantissa (the lowest 23 bits number) */
mantissa = float_conv.i & 0x7fffff;
/* the IEEE754 float assumes the highest bit on the mantissa is set, so set it */
mantissa |= 0x800000;
/* extract exponent (which is biased, so we unbias as well */
exponent = 150 - ((float_conv.i >> 23) & 0xff);
/* calculate the integer value */
result = mantissa;
if (exponent < 0) {
result <<= -exponent;
} else {
result >>= exponent;
}
/* handle sign */
if (float_conv.i & 0x80000000) {
result = -result;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment