Skip to content

Instantly share code, notes, and snippets.

@gabrielhamel
Created October 26, 2022 15:42
Show Gist options
  • Save gabrielhamel/df7e17b4e647fed1151d52dc586dd57e to your computer and use it in GitHub Desktop.
Save gabrielhamel/df7e17b4e647fed1151d52dc586dd57e to your computer and use it in GitHub Desktop.
Float analyser
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
void my_put_char(char c)
{
write(1, &c, 1);
}
void my_put_nbr_base(int nb, const char *base)
{
size_t base_value = strlen(base);
if (nb < 0) {
my_put_char('-');
nb *= -1;
}
if (nb >= base_value) {
my_put_nbr_base(nb / base_value, base);
}
my_put_char(base[nb % base_value]);
}
int main(int argc, char const *argv[])
{
setvbuf(stdout, NULL, _IONBF, 0);
float nb = -65.50009;
unsigned int hexNb = *(int *)&nb;
float sign = hexNb >> 31 ? -1 : 1;
// Si 1 alors négatif;
printf("Sign = ");
my_put_nbr_base(sign, "01");
printf(", (%c)\n", sign < 0 ? '-' : '+');
unsigned int exponent = ((hexNb & 0x7f800000) >> 23) - 127;
printf("Exponent = ");
my_put_nbr_base((hexNb & 0x7f800000) >> 23, "01");
printf(", (%d)\n", exponent);
unsigned int mantisse = hexNb & 0x7FFFFF;
printf("Mantisse = ");
my_put_nbr_base(mantisse, "01");
printf(", (%d)\n", mantisse);
double value = 0.5;
double res = 1;
for (int i = 0; i < 23; i++) {
// Get digit into the mantisse
res += ((mantisse >> (22 - i)) & 1) * value;
value /= 2;
}
for (int i = 0; i < exponent; i++) {
res *= 2;
}
printf("Value = %f\n", res * sign);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment