Right now I'm using this to set/unset individual bits in a byte:
if (bit4Set)
nbyte |= (1 << 4);
else
nbyte &= ~(1 << 4);
But, can't you do that in a more simple/elegant way? Like setting or unsetting the bit in a single operation?
Note: I understand I can just write a function to do that, I'm just wondering if I won't be reinventing the wheel.
Put it in a function, the bool type will enforce 0,1 for all bitval inputs.
Have you considered assigning mnemonics and/or identifiers to your bits, rather than referring to them by number?
As an example, let's say setting bit 4 initiates a nuclear reactor SCRAM. Instead of referring to it as "bit 4" we'll call it
INITIATE_SCRAM
. Here's how the code for this might look:This won't necessarily be any more efficient (after optimization) than your original code, but it's a little clearer, I think, and probably more maintainable.
This is a perfectly sensible and completely standard idiom.
This is tagged as C++ so have you considered using
std::bitset
instead of doing all the bit manipulation yourself? Then you can just use array notation as:bits[3] = bit4Set
to set the appropriate bit.If the right hand side of the assignment,
(1 << 4)
, is always a constant like this, then this would probably be optimized by compiler so it will be simpler in resulting assembly:Sure! It would be more obvious if you expanded the
|=
and&=
in your code, but you can write:Note that
bit4Set
must be zero or one —not any nonzero value— for this to work.