Setting nth bit of unsigned int
12,276
Solution 1
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
.)
Solution 2
x ^= (-y ^ x) & (1 << n);
Related videos on Youtube
Author by
user95297
Updated on July 28, 2022Comments
-
user95297 over 1 year
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.
-
segarci about 9 yearsPlease read How to ask.
-