Core S2 Software Solutions

Little trick for bit-wise optimization integer bound optimization

If you need to bind an integer between 0 and powers of 2 – 1(i.e. 1, 3, 7, 15, 31, etc.), you can use the bit-wise and operator to mask out irrelevant bits rather than apply modulo. The idea is I believe that this is faster to do on a processor than to do the modulo operator / code. It might even be the case that modern C compilers optimize for this! I’m even more curious if the hardware (x86) is smart enough to do this.

Put simply: essentially you take your integer, and apply bit-wise and logic to the number, so that all bits that represent a number higher than your limit are ignored, but yet you retain the relavent bits forming a binary number within your limits. You need to do this with powers of 2 – 1 because those numbers are all “filled” bit representations, so for example 3 is 11, 7 is 111, 15 is 1111.


1. Simple / standard approach:
int Bounded = rand() % 256

2. Bit-wise approach:
int Bounded = rand() & 255;

Same end result, but I believe (though without confirmation) that approach #2 is faster. Let me hear your thoughts!

Edit: As a friend just pointed out to me (he is a Comp. Eng. major, in my defense :P), I’m right that this optimization is commonly found in compilers and some processors. Wikipedia has a slightly better explanation on this corner-case optimization!

This entry was posted in News & Updates. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


Sites map