Decode a hex representation into a float
#include <stdio.h>
#include <string.h>
#include <math.h>
void hex_2_f(char* s)
{
int i;
long tmp = strtol(s, NULL, 16);
printf("String: %s, Parsed to: %x\n", s, tmp);
int sign = tmp >> 31;
int exp = ((tmp >> 23) & 0xFF);
int base = tmp & 0x7fffff;
float result = (1 - 2*sign)*(1 + (base*(powf(2,-23))))*(powf(2,exp-127));
printf("RESULT:: %f\n", result);
}
int main(int argc, char* argv[])
{
float f;
if (argc < 2)
{ printf("usage: %s [hex val to convert to float]\n", argv[0]);
}
else
{ hex_2_f(argv[1]);
}
}
Round a FP number to an epsilon
float hack(float in, float epsilon)
{
float in_p = in;
int steps = (int)log10(in / epsilon) + 1;
int start = (int)log10(in) ;
if (in < 1) start--;
float ans = 0.0;
while (true)
{
int tmp = (int)(in_p / pow10(start));
ans += tmp*pow10(start);
in_p -= tmp*pow10(start);
start--;
steps--;
if (!steps) break;
}
return ans;
}
int main(void)
{
printf("I GET %e\n", hack(789.145, .1));
return 1;
}
--
MattWalsh - 06 Aug 2009