1. 15

  2. 2

    To divide by 3, I used a multiplication trick. On tiny devices, division is often implemented as a (slow) library call, but if you’re dividing by a constant, you can usually find a good equivalent fixed-point constant. “One third” in binary is “0.5555…” repeating, so using a 16-bit fixed-point fraction, you can multiply by 0x5556 and shift right 16 bits.

    Why 0x5556 and not 0x5555?

    1. 7

      Because shifting right by 16 is the math equivalent of “floor” instead of “round”, so we need the result to be not just “as close to 1/3 as possible”, but the error needs to be on the high side instead of the low side.

      0x5555 * 3 = 0xffff – shifts right to zero

      0x5556 * 3 = 0x10002 – shifts right to one

      I’ll add this to the post, thanks!

      1. 1

        Thank you!

      2. 1

        Because the number 0.555555… is a little closer to 0.5556 than 0.5555. When they say “in binary” I think they mean “in hex” too.

        1. 2

          0x0.55555… is closer to 0x0.5555 than 0x0.5556. Remember, 0x0.5 is five sixteenths, significantly less than a half (which would be 0x0.8).

          1. 2

            Well corrected! I clearly fluffed that in my head.