re implement modulo using bit shifts?

后端 未结 5 1543
情歌与酒
情歌与酒 2021-02-07 16:10

I\'m writing some code for a very limited system where the mod operator is very slow. In my code a modulo needs to be used about 180 times per second and I figured that removing

5条回答
  •  孤街浪徒
    2021-02-07 16:43

    Every power of 16 ends in 6. If you represent the number as a sum of powers of 16 (i.e. break it into nybbles), then each term contributes to the last digit in the same way, except the one's place.

    0x481A % 10 = ( 0x4 * 6 + 0x8 * 6 + 0x1 * 6 + 0xA ) % 10
    

    Note that 6 = 5 + 1, and the 5's will cancel out if there are an even number of them. So just sum the nybbles (except the last one) and add 5 if the result is odd.

    0x481A % 10 = ( 0x4 + 0x8 + 0x1 /* sum = 13 */
                    + 5 /* so add 5 */ + 0xA /* and the one's place */ ) % 10
                = 28 % 10
    

    This reduces the 16-bit, 4-nybble modulo to a number at most 0xF * 4 + 5 = 65. In binary, that is annoyingly still 3 nybbles so you would need to repeat the algorithm (although one of them doesn't really count).

    But the 286 should have reasonably efficient BCD addition that you can use to perform the sum and obtain the result in one pass. (That requires converting each nybble to BCD manually; I don't know enough about the platform to say how to optimize that or whether it's problematic.)

提交回复
热议问题