Jump to content
  • Advertisement
Sign in to follow this  
Lode

Setting a bit of a byte

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Quote:
Original post by TDragon
a = a & (2^b)

Mathematically speaking.

That will zero all other bits.

Share this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by TDragon
a = 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 this post


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

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

Share this post


Link to post
Share on other sites
Quote:
Original post by Sneftel
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.


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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!