Wrap numbers around power of 2 borders

I was working yesterday on some texture sampler, and recalled a simple thingy that was a great help back in the 90′s, which I completely forgot in recent years. If you have a counter, sampler or whatever that has to get wrapped around e.g. 256, 512 or any other power of two, you can use the following ultra fast hack:

// Wrap around 2^10
int x = some_fn(x) & 1023;

This will wrap whatever x is, around 1024 limiter. For example if x is 1025, it will become 1. 1026 will turn over to 2 etc. Still better than:

x = some_fn(x);
x = x > 1023 ? x - 1024 : x;

Tags: ,

Leave a Comment