Reputation: 453
I have three unsigned 32-bit integers, say a
, b
, and c
. If the lowest bit of b
is 1, I want to XOR c
with a
, and store the result into c
. We can do this in the following way:
#include <cassert>
int main()
{
// Some values for a and c
unsigned a = 16;
unsigned c = 25;
unsigned b = 5; // 101_2
if(b & 1)
{
c ^= a;
}
assert(c == 9);
}
Can I do this conditionally without branching, that is, with no if-statements?
Upvotes: 1
Views: 470
Reputation: 2007
There's lots of ways to do this. Here's another, no multiply, only 4 operations.
c ^= a&(-(b&1));
Upvotes: 6
Reputation: 145839
Without if
statement and without branching you have to check the assembly dump of your compiler:
c ^= ~((b & 1) - 1) & a;
Upvotes: 3