Skip to content

Instantly share code, notes, and snippets.

@skejeton
Created July 28, 2022 22:35
Show Gist options
  • Save skejeton/e65c1a98683c3f728f9638f1baa0dab4 to your computer and use it in GitHub Desktop.
Save skejeton/e65c1a98683c3f728f9638f1baa0dab4 to your computer and use it in GitHub Desktop.
Add floats (non negative)
// DOES NOT WORK ON NEGATIVE VALUES !! :P
#include <stdio.h>
union MyFloat {
float fv;
struct {
unsigned mantissa: 23;
unsigned exponent: 8;
unsigned sign: 1;
} bv;
}
typedef MyFloat;
#define IMPLICIT_ONE (1u << 23u)
void dump(MyFloat f, const char *name) {
int x = ((int)f.bv.exponent - 127 - 23);
if (x < 0) {
x *= -1;
x = (f.bv.mantissa + IMPLICIT_ONE) >> x;
} else {
x = (f.bv.mantissa + IMPLICIT_ONE) << x;
}
printf("%s: %b %08b %d%023b %d\n", name, f.bv.sign, f.bv.exponent, f.bv.exponent > 0, f.bv.mantissa, x);
}
MyFloat fadd(MyFloat a, MyFloat b) {
if (a.bv.exponent <= b.bv.exponent) {
MyFloat tmp = a;
a = b;
b = tmp;
}
unsigned am = ((a.bv.exponent == 0) ? (a.bv.mantissa) : (a.bv.mantissa + IMPLICIT_ONE));
unsigned bm = ((b.bv.exponent == 0) ? (b.bv.mantissa) : (b.bv.mantissa + IMPLICIT_ONE));
unsigned diff = a.bv.exponent-b.bv.exponent;
unsigned new_mantissa = am + (bm >> diff);
if (new_mantissa >= (IMPLICIT_ONE << 1)) {
a.bv.exponent += 1;
new_mantissa &= ~IMPLICIT_ONE;
new_mantissa >>= 1;
}
return (MyFloat){.bv = {new_mantissa, a.bv.exponent, (a.bv.sign|b.bv.sign)}};
}
int main() {
MyFloat a = {9.234234};
MyFloat b = {2.934234};
dump(a, "a");
printf("%f + %f = %f\n", a.fv, b.fv, fadd(a, b).fv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment