Hi I'm implementing some fixed point math stuff for embedded systems and I'm trying to do the multiplication of two 16.16 fixed point numbers without creating a 64bit temporary. So far here is the code I came up with that generates the least instructions.
int multiply(int x, int y){
int result;
long long temp = x;
temp *= y;
temp >>= 16;
result = temp;
return result;
}
the problem with this code is that it uses a temporary 64 bit integer which seem to generate bad assembly code. I'm trying to make a system that uses two 32 bit integers instead of a 64 bit one. Anyone know how to do this?
Think of your numbers as each composed of two large "digits."
The "base" of the digits is the 2^bit_width, i.e., 2^16, or 65536.
So, the product is
However, to get the product shifted right by 16, you need to divide all these terms by 65536, so
In C:
The signed version is a bit more complicated; it is often easiest to perform the arithmetic on the absolute values of
x
andy
and then fix the sign (unless you overflow, which you can check for rather tediously).