Setting a bit of a byte
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.
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.
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.
Quote:Original post by TDragon
a = a & (2^b)
Mathematically speaking.
That will zero all other bits.
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.
I need to learn to think a little longer before I post. Meh.
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.
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 ||?
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
In C or C++:
perhaps?
1 left-shifted by x is equivalent to 2 raised to the power of x, btw.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement