1
Programming / Re: Angle wrapping in code, "easy" problem, need to double check
« Last post by Siwastaja on Today at 06:24:07 am »For angles that need to wrap, I'd suggest, instead of degrees, use 65536/360 deg (~ 0.005deg) as your base unit. (Or 2^32/360 if you need more resolution, or 256/360 if that suffices!). This way, wrap around always Just Works implicitly - and efficiently, in CPU registers directly (either with zero cost, or in worst case, requiring a single instruction to mask out bits):
uint16_t angle = ...;
uint16_t angle_plus_90deg = angle + 16384; // implicit correct wrapping guaranteed by C standard
...
You can further just choose to cast into signed type (int16_t) to interpret the angle between -180 .. +180 deg.
Only convert to degrees when interfacing with human, in UI.
In C, this is all standard; unsigned arithmetics are guaranteed to provide modulus operation when the result overflows, so if you ever came across with an oddball CPU architecture which does not do this on machine level, then the C compiler for that machine would still emit the correct instructions, and as such, the solution is portable.
uint16_t angle = ...;
uint16_t angle_plus_90deg = angle + 16384; // implicit correct wrapping guaranteed by C standard
...
You can further just choose to cast into signed type (int16_t) to interpret the angle between -180 .. +180 deg.
Only convert to degrees when interfacing with human, in UI.
In C, this is all standard; unsigned arithmetics are guaranteed to provide modulus operation when the result overflows, so if you ever came across with an oddball CPU architecture which does not do this on machine level, then the C compiler for that machine would still emit the correct instructions, and as such, the solution is portable.