You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add explanation of converting between floating and fixed point (#21)
* Add explanation of converting between floating and fixed point
This is useful in many situations, like when generating fixed point
constants, or when printing fixed point values for debugging (or non
debugging) purposes.
Also, fix some qualifiers (`extern` isn't needed, `const` is nice to
use).
* Update content/fixed-point-math.md
Co-authored-by: Antonio Vivace <avivace4@gmail.com>
* Add suggestion
---------
Co-authored-by: Antonio Vivace <avivace4@gmail.com>
// shift both of these values left to account for the fixed-point
@@ -163,10 +163,11 @@ Before adding or subtracting fixed-point numbers, you need to make the denominat
163
163
164
164
```c
165
165
// variable 'a' uses an unsigned 27.5f fixed-point format
166
-
int a_fp = 5;
166
+
constint a_fp = 5;
167
167
unsignedint a = 3 << a_fp;
168
+
168
169
// variable 'b' uses an unsigned 16.16f fixed-point format
169
-
int b_fp = 16;
170
+
constint b_fp = 16;
170
171
unsignedint b = 4 << b_fp;
171
172
```
172
173
@@ -206,6 +207,54 @@ Even though you can't do hardware-level division, there are usually creative wor
206
207
207
208
If you really must divide, you would multiply the numerator by the fixed-point first, *before* dividing.
208
209
210
+
## Converting between fixed and floating point
211
+
212
+
Now you have a way to do mathematical operations efficiently. How do you set the initial values in a convenient way? How do you print the values in a way that is easier to understand than very big integer values?
213
+
214
+
Well, you can convert between fixed and floating point easily:
215
+
216
+
```c
217
+
constint player_fp = 3;
218
+
219
+
staticinlineintplayer_float2fixed(float value)
220
+
{
221
+
return (int)(value * (1 << player_fp));
222
+
}
223
+
224
+
static inline float player_fixed2float(int value)
225
+
{
226
+
return value / (float)(1 << player_fp);
227
+
}
228
+
229
+
// Macro version of the functions, for situations where you can't use functions
Remember that those are floating point operations, so they will be slow. There is an exception: if you use `constexpr` or if the compiler detects that an expression is constant, it will calculate it at compile time automatically. This is very useful for setting initial fixed point values from floating point values.
244
+
245
+
```c
246
+
int player_x, player_y;
247
+
248
+
constexpr int player_start_x = player_float2fixed(1.23); // Only in C++
249
+
const int player_start_y = PLAYER_FLOAT2FIXED(2.35);
250
+
251
+
int setup(void)
252
+
{
253
+
player_x = player_start_x;
254
+
player_y = player_start_y;
255
+
}
256
+
```
257
+
209
258
And there you go! You now know everything needed to do fixed-point math. Good luck!
0 commit comments