Skip to content

Instantly share code, notes, and snippets.

@lynn
Last active March 15, 2020 15:54
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 lynn/a611d8c8cb64faa380c1685cae2bae45 to your computer and use it in GitHub Desktop.
Save lynn/a611d8c8cb64faa380c1685cae2bae45 to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <stdio.h>
typedef float f32;
typedef int32_t i32;
f32 mod1(f32 f) {
i32 i = *(i32*)&f;
i32 e = (i >> 23) & 0xff;
i32 m = i & 0x7fffff;
if (e == 255) { /* inf or nan */
i = 1 | (e << 23); /* nan */
} else if (e >= 127) { /* >= 1 */
/* keep the fractional bits */
if (e - 127 >= 32) return 0.0f;
m &= 0x7fffff >> (e - 127);
if (m == 0) return 0.0f;
/* renormalize */
while (!(m & 0x800000)) e--, m <<= 1;
m &= 0x7fffff;
i = m | (e << 23) | (i & 0x80000000);
}
return *(f32*)&i;
}
int main() {
printf("%f\n", mod1(123.45));
printf("%f\n", mod1(1.0/0.0));
printf("%f\n", mod1(0.000123));
printf("%f\n", mod1(-1234.000123));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment