A fixed-point number is a representation of a real number using a certain number of type bits for the integer part, and the remaining type bits for the fractional part. The number of bits representing each part is fixed (hence the name, fixed point). An integer type is commonly used to store fixed-point values.
Fixed-point numbers are commonly used on systems that do not support floating point, or require more speed than a floating point can provide. Fixed point calculations can be performed using integer CPU instructions.
A 32-bit fixed-point number will be stored in a 32-bit type, such as int .
Typically, each bit in an integer type (unsigned in this case) will represent an integer value of 2 ^ n as follows:
1 0 1 1 0 0 1 0 = 2^7 + 2^5 + 2^4 + 2^1 = 178 2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
But if the type is used to store the value of a fixed point, the bits are interpreted somewhat differently:
1 0 1 1 0 0 1 0 = 2^3 + 2^1 + 2^0 + 2^-3 = 11.125 2^3 2^2 2^1 2^0 2^-1 2^-2 2^-3 2^-4
The fixed point number in the above example is called the fixed point number 4.4, since there are 4 bits in the binary part and 4 bits in the fractional part of the number. In the 32-bit type, the fixed-point value will usually be in the 16.16 format, but it can also be 24.8, 28.4, or any other combination.
Converting from a floating point value to a fixed point value includes the following steps:
- Multiply the float by 2 ^ (the number of fractional bits for the type), for example. 2 ^ 8 for 24.8
- If necessary, round the result (just add 0.5) and place it (or drop it to an integer type), leaving the integer value.
- Assign this value to a fixed point type.
Obviously, you may lose some precision in the fractional part of the number. If the accuracy of the fractional part is important, the choice of fixed-point format may reflect this - for example. use 16.16 or 8.24 instead of 24.8.
Negative values ββcan also be processed the same way if you need to specify a fixed point number.
If my Java were stronger, I would try some code, but usually I write such things in C, so I will not try to use the Java version. Also, the stacker version looks good to me, with the slight exception that it does not offer rounding capabilities. It even shows you how to do multiplication (shift is important!)