What you want to do is modular arithmetic. Your machine with two additions already does this with integer math. Thus, by comparing your values ββin arithmetic with two additions, you can get the modolo operation for free.
The trick represents your angle as a fraction of 360 degrees between 0 and 1 epsilon. Of course, then your constant angles should be displayed the same way, but it should not be hard; it's just the math we can hide in the transform function (er, macro).
The meaning in this idea is that if you add or subtract angles, you get the value, part of which you want and whose whole part you want to throw away. If we represent a fraction as a 32-bit fixed-point number with a binary point of 2 ^ 32 (for example, to the left of what is usually considered a sign bit), any fraction overflows just drop from the top of the 32-bit value for free. So, you do all the math, and the removal of "overflow" is free.
So, I rewrote your code (keeping the idea of ββdegrees 10 times):
typedef unsigned int32 angle;
I did not compile or run this code.
Changes made to make these degrees of time 100 or 1 fairly easy; change the angle_scale_factor parameter. If you have a 16-bit machine, switching to 16 bit is likewise easier; if you have 32 bits and you still want to do only 16-bit math, you will need to mask the value to be printed to 16 bits.
This solution has another nice feature: you documented which variables are angles (and have funny ideas). The OP source code just called them ints, but thatβs not what they represent; the future maintainer will be surprised by the source code, especially if he finds a subtraction extracted from the variables.
Ira Baxter
source share