fork download
  1. /* vim: ft=c ff=unix fenc=utf-8
  2.  * file: xx.c
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdint.h>
  7. #include <stdbool.h>
  8. #include <string.h>
  9. #include <unistd.h>
  10. #include <math.h>
  11.  
  12. /* input bin data *MUST* be eq 32 bits in little-endian byte order */
  13. float
  14. bin2float (unsigned char *bin) {
  15. float result = 1.f; /* declare with imaginary unit */
  16. int e = bin[3] - 127;
  17. int bitno;
  18. /* first byte (7 bits) */
  19. for (bitno = 7; bitno > -1; bitno--)
  20. if (bin[2] & (1 << bitno))
  21. result += pow(2, -1 * (7 - bitno));
  22. /* second octet */
  23. for (bitno = 8; bitno > -1; bitno--)
  24. if (bin[1] & (1 << bitno))
  25. result += pow(2, -1 * (8 - bitno + 7));
  26. /* third octet */
  27. for (bitno = 8; bitno > -1; bitno--)
  28. if (bin[0] & (1 << bitno))
  29. result += pow(2, -1 * (8 - bitno + 15));
  30. result *= pow(2, e);
  31. /* check invert bit */
  32. if (bin[2] & 0x80)
  33. result *= -1;
  34. return result;
  35. }
  36.  
  37. int
  38. main (int argc, char *argv[])
  39. {
  40. unsigned char x[] = {0x00, 0x00, 0x72, 0x81};
  41. printf("%f\n", bin2float(x));
  42. return EXIT_SUCCESS;
  43. }
  44.  
  45.  
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
7.562500