An Innovative Use of Right Shifting in C/C++

When I was optimizing a piece of C++ code, I noticed a very odd behavior of C++ programs in handling shiftings, that right shifting a negative integer to its least significant 1 will result a -1.


int16_t i = (1 << 15) >> 15;
printf("%d\n", i);
> -1

This bit hacking techinique could be beneficial in optimizing some C++ programs. For example, here is a simple comparison between two integers, it conducts as following

// a generic approach
if (a > b) tmp = a;
else if (a < b>) tmp = b;

The generic approach is equivalent with the following piece of code, but shows a better performance

// a bit hacking approach
int mask = (a-b) >> 31;
tmp = (mask & a) | (~mask & b);