misc : fixed point arithmitic
Structure
So a nubmer is made of a whole part and a fractional part. So something that's 4:4 has the high-nibble is the whole part,
and the low-nibble is the fractional part. So for unsigned numbers, the range of the above would be 0 to 15 for the whole part.
The fractional part works very much the same, except kinda in reverse. The highest order bit of the fractional part is 1/(2^1), or .5.
The next highest is 1/(2^2), and so on. So with 4 bits, the largest fractional part you can use is 1/2 + 1/4 + 1/8 + 1/16 = 15/16th.
So the total range of an unsigned 4:4 fixed point number is 0 to 15 + 15/16.
Operations
- Addition - Normal integer division. It just works out [work out some examples to prove this to yourself.
- Subtraction - same as above.
- Multiplication - Can use normal integer multiplication, but if you start with two 4:4's, the result is going to be
an 8:8, so to convert it back down to a 4:4, you would shift it right by 4, and mask it to 0xff.
- Divivision - Think the opposite of multiplication. Convert the numerator to an 8:8, do normal integer division with the 4:4,
and your result will be a 4:4. If you can't afford that many bits, you can perform the equivalent of long division. Sure there
are better solutions online though.