Skip to content

Instantly share code, notes, and snippets.

@madmann91
Last active July 22, 2016 13:56
Show Gist options
  • Save madmann91/26dd12915e92026c561f8b60a24c0c63 to your computer and use it in GitHub Desktop.
Save madmann91/26dd12915e92026c561f8b60a24c0c63 to your computer and use it in GitHub Desktop.
Manipulation of the IEEE floating point representation.
#include <stdio.h>
int as_int(float f) {
union { float f; int i; } u;
u.f = f;
return u.i;
}
float as_float(int i) {
union { float f; int i; } u;
u.i = i;
return u.f;
}
float encode_float(int s, int e, int m) {
return as_float(s | e << 23 | m & 0x7FFFFF);
}
float fracf(float f) {
int i = as_int(f);
int e = (i >> 23) & 0xFF;
int m = i & 0x7FFFFF;
return encode_float(0, 127, m << (e - 127)) - 1.0f;
}
int main() {
printf("%f\n", fracf(-12877.212f));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment