Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminating IF statement using bitwise operators

I am trying to eliminate an IF statement whereby if I receive the number 32 I would like a '1', but any other number I would like a '0'.

32 is 0010 0000 so I thought about XOR-ing my input number with 1101 1111. Therefore if I get the number 32 I end up with 1111 1111.

Now is there any way of AND-ing the individual bits (1111 1111), because if one of my XOR results is a 0, it means my final AND-ed value is 0, otherwise its a 1?

EDIT: Using GCC, not Intel compiler (because I know there are a lot of intrinsic functions there)

like image 249
user997112 Avatar asked Nov 18 '25 22:11

user997112


1 Answers

The expression

  !(x ^ 32)

will do the trick for you if you insist.

That will always work in C, and will also work in almost all C++ settings. Technically in C++ it evaluates to a boolean which in almost all circumstances will work like 0 or 1, but if you want a technically correct C++ answer:

  (0 | !(x^32))

or:

(int)!(x ^ 32)

or with the more modern / verbose C++ casting

static_cast<int>(x ^ 32)
like image 148
abligh Avatar answered Nov 20 '25 11:11

abligh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!