Advertisement
joachip

Cowboy style 24-bit int to ieee float conversion

Dec 2nd, 2015
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. /*
  2. Insano 24-bit integer to ieee float conversion by JoaCHIP. Winners do drugs. Here be dragons.
  3. Assumptions: Your FPU uses ieee float and your CPU uses reverse "intel" byte order.
  4. Expected output:
  5.  
  6.     -8388605 ---> -1.000000
  7.     -6710884 ---> -0.800000
  8.     -5033163 ---> -0.600000
  9.     -3355442 ---> -0.400000
  10.     -1677721 ---> -0.200000
  11.     +0000000 ---> +0.000000
  12.     +1677721 ---> +0.200000
  13.     +3355442 ---> +0.400000
  14.     +5033163 ---> +0.600000
  15.     +6710884 ---> +0.800000
  16.     +8388605 ---> +1.000000
  17.  
  18. */
  19.  
  20.  
  21. #include <stdio.h>
  22.  
  23. int main()
  24. {
  25.     unsigned char input[4];
  26.  
  27.     for (int a=-5; a<=5; a++)
  28.     {
  29.         // just some weird example value that goes from appx. the lowest 24-bit integer value -8388608 to the highest +8388607
  30.         int audiosample = a * (8388607 / 5);
  31.  
  32.         // and here comes the insane int to ieee float conversion (it's okay to be scared)
  33.         unsigned char input[4];
  34.         input[3] = ((audiosample>>23) & 1) << 7 | 64;
  35.         input[2] = (audiosample>>17) & 0x7F;
  36.         input[1] = (audiosample>>9) & 0xFF;
  37.         input[0] = (audiosample>>1) & 0xFF;
  38.         float result = audiosample>=0 ? (*((float*)input))-2.0f : -4.0f-(*((float*)input));
  39.  
  40.         // print out result
  41.         printf("%+08d ---> %f\n", audiosample, result);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement