fork download
  1. #include <stdio.h>
  2.  
  3. typedef struct
  4. {
  5. signed short m;
  6. unsigned char f;
  7. } Q16_8;
  8.  
  9. Q16_8 toQ(double d)
  10. {
  11. Q16_8 q;
  12. long x = d * 256;
  13. q.m = x / 256; // this assumes >> to be an arithmetic shift
  14. q.f = x & 0xFF; // this assumes signed ints to be 2's complement
  15. return q;
  16. }
  17.  
  18. double toDouble(Q16_8 q)
  19. {
  20. long x = ((long)q.m << 8) + q.f;
  21. return x / 256.0;
  22. }
  23.  
  24. int main(void)
  25. {
  26. int i;
  27. for (i = -2*4; i <= +2*4; i++)
  28. {
  29. double d = i / 4.0;
  30. Q16_8 q = toQ(d);
  31. double d2 = toDouble(q);
  32. printf("toDouble(toQ(%f)) = %f\n", d, d2);
  33. }
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
toDouble(toQ(-2.000000)) = -2.000000
toDouble(toQ(-1.750000)) = -0.750000
toDouble(toQ(-1.500000)) = -0.500000
toDouble(toQ(-1.250000)) = -0.250000
toDouble(toQ(-1.000000)) = -1.000000
toDouble(toQ(-0.750000)) = 0.250000
toDouble(toQ(-0.500000)) = 0.500000
toDouble(toQ(-0.250000)) = 0.750000
toDouble(toQ(0.000000)) = 0.000000
toDouble(toQ(0.250000)) = 0.250000
toDouble(toQ(0.500000)) = 0.500000
toDouble(toQ(0.750000)) = 0.750000
toDouble(toQ(1.000000)) = 1.000000
toDouble(toQ(1.250000)) = 1.250000
toDouble(toQ(1.500000)) = 1.500000
toDouble(toQ(1.750000)) = 1.750000
toDouble(toQ(2.000000)) = 2.000000