re implement modulo using bit shifts?

后端 未结 5 1544
情歌与酒
情歌与酒 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:50

    Doing modulo 10 with bit shifts is going to be hard and ugly, since bit shifts are inherently binary (on any machine you're going to be running on today). If you think about it, bit shifts are simply multiply or divide by 2.

    But there's an obvious space-time trade you could make here: set up a table of values for out and out % 10 and look it up. Then the line becomes

      out += tab[out]
    

    and with any luck at all, that will turn out to be one 16-bit add and a store operation.

提交回复
热议问题