C/C++ Bit Twiddling C/C++ Bit Twiddling c c

C/C++ Bit Twiddling


I would try

x -= (pow2 ^ (~sgn+1)) + sgn

or, as suggested by lijie in the comments

x -= (pow2 ^ -sgn) + sgn

If sgn is 0, ~sgn+1 is also 0, so pow2 ^ (~sgn+1) == pow2. If sgn is 1, (~sgn+1) is 0xFFFFFFFF, and (pow2 ^ (~sgn+1)) + sgn == -pow2.


mask = sgn - 1; // generate mask: sgn == 0 => mask = -1, sgn == 1 => mask = 0x = x + (mask & (-pow2)) + (~mask & (pow2)); // use mask to select +/- pow2 for addition


Off the top of my head:

int subMask = sgn - 1;x -= pow2 & subMask;int addMask = -sgn;x += pow2 & addMask;

No guarantees on whether it works or whether this is smart, this is just a random idea that popped into my head.

EDIT: let's make this a bit less readable (aka more compact):

x += (pow2 & -sgn) - (pow2 & (sgn-1));