Bitwise binary overflow at less than 0-255, e.g. 0-32?

Viewed 85

I use unsigned byte's 0-255 binary overflow / wraparound, as this saves on certain bounds checks (conditional branches) in a infinitely wrapping game world.

Is there a way, using bit operators, to wrap on an arbitrary power-of-2 value, e.g. 2^5 = 32?

This would happen non-conditionally, so that if the value were >= 32, we'd wrap as usual, and if it were < 32, the value would remain the same.

1 Answers

Yes, you can just and the value with a mask. So if you want your value modulo 32 you can do

x = x & 31;

That will limit the value to the least significant 5 bits. (In other words, this works for all wraparounds that are a power of 2)

Related