Skip to content

Instantly share code, notes, and snippets.

@panta
Created December 10, 2021 13:40
Show Gist options
  • Save panta/097dce8cc1b80396cb3bf27f88142d48 to your computer and use it in GitHub Desktop.
Save panta/097dce8cc1b80396cb3bf27f88142d48 to your computer and use it in GitHub Desktop.
UNIPD FdI 2021-2022 - Conversioni float da/verso codifica a 32 bit.
#include <stdio.h>
#include <stdint.h>
// NOTA: queste funzioni operano correttamente solo sulle piattaforme
// in cui float occupa esattamente 32 bit!
// (Solitamente vero in C99 e garantito in C99 su x86 e amd64)
// float_to_repr32() ritorna l'intero a 32 bit
// che "codifica" il float passato come argomento
// secondo IEEE754.
int32_t float_to_repr32(float value) {
int32_t *ip = (int32_t *)&value;
return *ip;
}
// repr32_to_float() ritorna il float
// "codificato" (secondo IEEE754) dall'intero a 32 bit
// passato come argomento.
float repr32_to_float(int32_t repr32) {
float *fp = (float *)&repr32;
return *fp;
}
int main() {
printf("sizeof(float): %d bytes\n\n", (int)sizeof(float));
float f1 = -123;
int32_t r1 = float_to_repr32(f1);
printf("%f -> 0x%08X\n", f1, (unsigned)r1);
printf("\n-------\n\n");
int32_t r2 = 0xC2F60000;
float f2 = repr32_to_float(r2);
printf("0x%08X -> %f\n", (unsigned)r2, f2);
printf("\n-------\n\n");
// azzera il bit più alto (bit 31) - bit di segno
int32_t r3 = 0xC2F60000 & ((int32_t)~(1 << 31));
float f3 = repr32_to_float(r3);
printf("0x%08X -> %f\n", (unsigned)r3, f3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment