Setting nth bit of unsigned int

12,276

Solution 1

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

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

Solution 2

x ^= (-y ^ x) & (1 << n);
Share:
12,276

Related videos on Youtube

user95297
Author by

user95297

Updated on July 28, 2022

Comments

  • user95297
    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.