Lets suppose that a = 2^k
is there any difference in terms of performance or correctness between int c = b%a
and int c = b & (a-1)
?
For two’s complement int
and a
a power of two, b % a
equals b & a-1
if and only if b
is non-negative or a multiple of a
.
As a consequence, a compiler can replace b % a
by b & a-1
only if it knows b
is non-negative or knows it is a multiple of a
. (In the latter case, it should replace the expression with zero.) On typical current processors, an AND and a subtract instruction will be at least as fast, and often faster, than a remainder (divide) instruction, so b & a-1
is preferred, and the programmer seeking performance should use it if they know the conditions are satisfied, unless they are sure the compiler will generate an AND for b % a
or they also want the quotient b/a
. (If the quotient is desired, the compiler must generate a divide instruction, and processors typically provide the remainder along with the quotient.)
Of course, the compiler can be assured that b
is non-negative by making it an unsigned int
. Ensuring the compiler knows that a
is a power of two is more complicated, unless a
is a constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With