daily pastebin goal
42%
SHARE
TWEET

Int-multiply-using-floats trickery

a guest Jul 6th, 2011 246 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. static float fnms(float a, float b, float c)
  5. {
  6.   return (float) -((double) a * (double) b - (double) c);
  7. }
  8.  
  9. int main()
  10. {
  11.   union
  12.   {
  13.     float f;
  14.     unsigned u;
  15.   } u;
  16.  
  17.   const float a = 255.0f;
  18.   const float aScaled = -a * pow(2.0f, 23.0f);
  19.  
  20.   for (int b=0; b < 65536; b++)
  21.   {
  22.     u.u = 0x3f800000 | b;
  23.     float product = fnms(u.f, aScaled, aScaled);
  24.     int prodAsInt = (int) product;
  25.     if (prodAsInt != a*b)
  26.     {
  27.       printf("Mismatch! b=%d\n", b);
  28.       return 1;
  29.     }
  30.   }
  31.  
  32.   return 0;
  33. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top