How do you multiply two fixed point numbers?
fixed-point, multiplication
Solution
You should use 2's complement representation instead of a seperate sign bit. It's much easier to do maths on that, no special handling is required. The range is also improved because there's no wasted bit pattern for negative 0. To multiply, just do as normal fixed-point multiplication. The normal Q2.14 format will store value x/214 for the bit pattern of x, therefore if we have A and B then
So you just need to multiply A and B directly then divide the product by 214 to get the result back into the form x/214 like this
AxB = ((int32_t)A*B) >> 14;
A rounding step is needed to get the nearest value. You can find the way to do it in Q number format#Math operations. The simplest way to round to nearest is just add back the bit that was last shifted out (i.e. the first fractional bit) like this
AxB = (int32_t)A*B;
AxB = (AxB >> 14) + ((AxB >> 13) & 1);
You might also want to read these
- Fixed-point arithmetic.
- Emulated Fixed Point Division/Multiplication
- Fixed point math in c#?
With 2 bits you can represent the integer range of [-2, 1]. So using Q2.14 format, -0.25 would be stored as `11.11000000000000`. Using 1 sign bit you can only represent -1, 0, 1, and it makes calculations more complex because you need to split the sign bit then combine it back at the end.
Problem
I am currently trying to figure out how to multiply two numbers in fixed point representation. Say my number representation is as follows: ``` [SIGN][2^0].[2^-1][2^-2]..[2^-14] ``` In my case, the number `10.01000000000000 = -0.25`. How would I for example do `0.25x0.25` or `-0.25x0.25` etc? Hope you can help!