AND faster than integer modulo operation?

后端 未结 6 1190
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 09:19

It is possible to re-express:

  • i % m

as:

  • i & (m-1)

where,

  • i is an unsigned integer
  • m is a po
6条回答
  •  感动是毒
    2021-02-14 10:01

    If m is known at compile time (or even it it isn't) integer division and modulo can be re-expressed using multiplication by a magic "multiplicative inverse." The result of the division ends up in the high 32 bits and the remainder (modulus) in the lower 32 bits:

    http://www.hackersdelight.org/magic.htm

    The following link claims that it is a standard compiler strength reduction:

    http://www.flounder.com/multiplicative_inverse.htm

提交回复
热议问题