Gideon
Gideon

Reputation: 453

XOR conditionally without branching if the lowest bit is set

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

Answers (3)

Steve Cox
Steve Cox

Reputation: 2007

There's lots of ways to do this. Here's another, no multiply, only 4 operations.

c ^= a&(-(b&1));

Upvotes: 6

Slava
Slava

Reputation: 44258

This should work

c ^= a * ( b & 1 );

Upvotes: 4

ouah
ouah

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

Related Questions