Angles, integers, and modulo arithmetic

Originally posted to Shawn Hargreaves Blog on MSDN, Monday, January 4, 2010

These days most people represent angles using degrees or radians, but many old-skool game programmers preferred a binary integer format where a full circle is 65536. To convert:

    short ToBinary(float degrees)
    {
        return (short)(degrees * 65536 / 360);
    }

If you store such a value in a 16 bit integer type, it will automatically overflow any time you increment it past a full circle, so you no longer need special case wrapping code to handle the circular (modulo) nature of angle arithmetic.

When manipulating degrees using floats, you might have to write:

    angle += turnAmount;

    if (angle >= 360)
        angle -= 360;
    else if (angle < 0)
        angle += 360;

But with a binary angle represented as a short, you can get the same result with just:

    angle += turnAmount;

This simplifies many common angle computations. For instance the TurnToFace method from the Aiming sample would no longer need to bother calling WrapAngle if it used this binary format.

Back in the day most games used integer or fixed point math, so this was a major win. But today most people use floating point, and converting between integer and float formats is awkward and slow. So it is debatable whether this format is still useful.

Blog index   -   Back to my homepage