Setting the nth bit unsigned int

Given 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 for this, while avoiding the use of any conditional operators? Thank.

+4
source share
2 answers
x = (x & (~(1 << n))) | (y << n)

Pretty simple. (First clear the nith bit and set the nith bit to 1, if y- 1.)

+3
source
x ^= (-y ^ x) & (1 << n);
0
source

All Articles