Skip to content

Instantly share code, notes, and snippets.

@samclane
Created September 21, 2017 19:43
Show Gist options
  • Save samclane/9d46a9bb40a6cebee02f456c2cc1e0b8 to your computer and use it in GitHub Desktop.
Save samclane/9d46a9bb40a6cebee02f456c2cc1e0b8 to your computer and use it in GitHub Desktop.
A special struct for floating point numbers which allows higher accuracy
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define DISPLAY_BUFFER_SIZE 5
typedef struct FixedFloat
{
int upper;
int lower;
int numLowerDigits;
}FixedFloat;
FixedFloat createFixedFloat(int upper, int lower, int numLowerDigits)
{
FixedFloat x = {.upper = upper, .lower = lower, .numLowerDigits = numLowerDigits};
return x;
}
double getValueFromFixedFloat(const struct FixedFloat fixed_float)
{
return fixed_float.upper + (fixed_float.lower / powf(10, fixed_float.numLowerDigits));
}
char * getStringFromFixedFloat(const struct FixedFloat fixed_float)
{
char * output = malloc(DISPLAY_BUFFER_SIZE);
sprintf(output, "%d.%d", fixed_float.upper, fixed_float.lower);
return output;
}
int main()
{
FixedFloat y = createFixedFloat(123, 45, 2);
printf("%f\n", getValueFromFixedFloat(y));
printf("%f\n", 123 + (45 / powf(10, 2)));
printf("%f\n", 123.);
printf("%f\n", (45 / powf(10, 2)));
printf("%s", getStringFromFixedFloat(y));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment