Last active
March 15, 2020 15:54
-
-
Save lynn/a611d8c8cb64faa380c1685cae2bae45 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
#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