AND faster than integer modulo operation?

后端 未结 6 1815
自闭症患者
自闭症患者 2021-02-14 09:34

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:17

    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

提交回复
热议问题