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.
Asked
Active
Viewed 1.4k times
8
-
1Please read [How to ask](http://stackoverflow.com/help/how-to-ask). – segarci Feb 06 '15 at 07:26
2 Answers
10
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
.)

minmaxavg
- 686
- 6
- 21
-
-
-
@Eun By condition I meant without having to check the value of y using an if-else statement or something similar. – user95297 Feb 06 '15 at 07:40
-
3...or, more cleaner: `x = (x | (1 << n)) & (y << n)` - this version sets `n`th bit to 1 in the first place. – minmaxavg Jun 12 '16 at 09:34
2
x ^= (-y ^ x) & (1 << n);

Emil Laine
- 41,598
- 9
- 101
- 157
-
-
I am aware of this, but I am wondering if it is possible to incorporate y into the expression so that both cases (with y being 0 or 1) can be handled with one statement. – user95297 Feb 06 '15 at 07:31
-