Skip to content

Instantly share code, notes, and snippets.

@lynn lynn/mod1.c
Last active Mar 15, 2020

Embed
What would you like to do?
#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
You can’t perform that action at this time.