Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Bit Twiddling

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!

like image 762
fs. Avatar asked Nov 25 '10 08:11

fs.


People also ask

What is bit twiddling function?

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.

What are bitwise operators in C++?

In C++, bitwise operators perform operations on integer data at the individual bit-level. These operations include testing, setting, or shifting the actual bits.


2 Answers

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.

like image 97
Sven Marnach Avatar answered Sep 25 '22 06:09

Sven Marnach


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
like image 30
Paul R Avatar answered Sep 26 '22 06:09

Paul R