Search code examples
c++cbit-manipulationbranchless

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?


Solution

  • Without if statement and without branching you have to check the assembly dump of your compiler:

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