# Setting a bit of a byte

This topic is 4907 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

If there's an unsigned char a, and a boolean b. Say x is a number from 0 to 7. I want to set bit x of a to b, without modifying the other bits. What's the shortest way to do this with C++ code? I tried all sorts of things with >>, <<, & and | operators but it looks pretty bad.

##### Share on other sites
a = a && ~(1 << x); // unconditionally zero-out bit "x" of "a" by ANDing "a" with all bits except bit "x"
if(b) a = a || (1 << x); // if b is true, set bit x

There are other ways to do it, but this should make the operation clear.

##### Share on other sites
a = a | (2^x)

Mathematically speaking. That sets bit x.

##### Share on other sites
Quote:
 Original post by TDragona = a & (2^b)Mathematically speaking.

That will zero all other bits.

##### Share on other sites
Ahem. OR. I mean OR, not AND. Excuse me. Major edits to my previous post...

I need to learn to think a little longer before I post. Meh.

##### Share on other sites
Quote:
 Original post by TDragona = a | (2^x)Mathematically speaking. That sets bit x.

That's half of what you need to do, but it will not zero bit x if it is set already.

##### Share on other sites
Quote:
 Original post by Sneftelif(b) a = a || (1 << x); // if b is true, set bit x

Shouldn't that be a single |, not a double ||?

##### Share on other sites
Quote:
 Original post by Sneftela = a && ~(1 << x); // unconditionally zero-out bit "x" of "a" by ANDing "a" with all bits except bit "x"if(b) a = a || (1 << x); // if b is true, set bit xThere are other ways to do it, but this should make the operation clear.

I think you meant to use bitwise operators here, yeah?

a = a & ~(1 << x); // unconditionally zero-out bit "x" of "a" by ANDing "a" with all bits except bit "x"
if(b) a = a | (1 << x); // if b is true, set bit x

##### Share on other sites
Indeed. DARN YOU, BITWISE OPERATIONS! YOU HAVE THWARTED ME FOR THE SECOND-TO-LAST TIME!

##### Share on other sites
In C or C++:
a = b ? a | (1 << x) : a & ~(1 << x);

perhaps?

1 left-shifted by x is equivalent to 2 raised to the power of x, btw.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 14
• 46
• 22
• 27
• ### Forum Statistics

• Total Topics
634048
• Total Posts
3015233
×