in the spirit of graphics.stanford.edu/~seander/bithacks.html I need to solve the following problem:
int x;
int pow2; // always a positive power of 2
int sgn; // always either 0 or 1
// ...
// ...
if(sgn == 0)
x -= pow2;
else
x += pow2;
Of course I need to avoid the conditional. So far the best I came up with is
x -= (1|(~sgn+1))*pow2
but that involves a multiplication which I also would like to avoid. Thanks in advance.
EDIT: Thanks all,
x -= (pow2^-sgn) + sgn
seems to do the trick!
Bit-twiddling version: boolean isPowerOf2(int x) { return x > 0 && (x & (x - 1)) == 0; } This function returns true if x == 1, 2, 4, 8, 16, ..., 1073741824 but false otherwise. To start, the condition x > 0 excludes numbers that cannot possibly be a positive integral power of 2.
In C++, bitwise operators perform operations on integer data at the individual bit-level. These operations include testing, setting, or shifting the actual bits.
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 = 0
x = x + (mask & (-pow2)) + (~mask & (pow2)); // use mask to select +/- pow2 for addition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With