C++ – Simple Way to Set/Unset an Individual Bit

bit-manipulationc++

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.

Best Answer

Sure! It would be more obvious if you expanded the |= and &= in your code, but you can write:

nbyte = (nbyte & ~(1<<4)) | (bit4Set<<4);

Note that bit4Set must be zero or one —not any nonzero value— for this to work.

Related Question