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.
x = (x & (~(1 << n))) | (y << n)
Quite simple. (First, clear the n
th bit, and set n
th bit to 1
if y
is 1
.)
x ^= (-y ^ x) & (1 << n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With