-
-
Save orlp/f29a0a7813df398fc494 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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