8

Given a unsigned int x, I want to set the nth bit to y, and y can be either 0 or 1. Is it possible to create an expression using bitwise operators to do this while avoiding the use of any conditional statements? Thanks.

user95297
  • 83
  • 1
  • 1
  • 4

2 Answers2

10
x = (x & (~(1 << n))) | (y << n)

Quite simple. (First, clear the nth bit, and set nth bit to 1 if y is 1.)

minmaxavg
  • 686
  • 6
  • 21
2
x ^= (-y ^ x) & (1 << n);
Emil Laine
  • 41,598
  • 9
  • 101
  • 157