Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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.

share|improve this question
    
Please read How to ask. – segarci Feb 6 at 7:26
up vote 1 down vote accepted
x = (x & (~(1 << n))) | (y << n)

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

share|improve this answer
    
Still this has a condition, even if it is in one line. – Eun Feb 6 at 7:39
    
Thank you! I never considered doing it this way. – user95297 Feb 6 at 7:39
    
@Eun By condition I meant without having to check the value of y using an if-else statement or something similar. – user95297 Feb 6 at 7:40
x ^= (-y ^ x) & (1 << n);
share|improve this answer
    
This is not unconditional. OP wants this without any condition – Eun Feb 6 at 7:30
    
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 6 at 7:31
    
@Eun Sorry you're right, I missed that. Fixed my answer. – zenith Feb 6 at 7:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.