Guest User

Int-multiply-using-floats trickery

a guest
Jul 6th, 2011
362
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

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×