How to Set, Clear, and Toggle a Single Bit?
Bit manipulation is an important part of programming. It is used to manipulate individual bits of data within a larger data structure or set of instructions. In this Q&A Session, we will discuss how to set, clear, and toggle a single bit.
Setting a Bit
The bitwise OR operator (
|) can be used to set a bit. The following line of code sets the
nth bit of
number |= 1UL << n;
number is wider than an unsigned long type then use
1ULL. This will ensure that promotion of
(1UL << n), which happens after evaluating the expression, does not cause undefined behavior by shifting more than the width of a long.
Clearing a Bit
The bitwise AND operator (