Life Pro Tip: the logical bit

There are many cases where you need to add a bit to an integer to indicate certain types of logic.
Say for example that you need a bit to indicate a ‘special’ state to a counter but you dont want to create a new variable.
I have seen crazy things like this:

The assumption was that there would be never more than 9,000 symbols on the stock market. Well one day it happened when someone added the pink sheets!
Of course you could do something more C++-ish like

But that often has performance implications that I’d not be so keen to pay.
So here is what would be a faster alternative:

This solution creates two problems:
1. Numbers are very close to their maximum limits and it’s very easy to make a mistake
2. It makes numbers too far apart in the scale, which can make things like pseudo-hashing impossible
Instead, just do the opposite: add a bit in the back, not at the front.

An additional advantage is that this can be used in a template class where uint64_t is typename T of integral type without concerns for sign or size of the type.

Leave a Reply

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