How to set, clear or toggle a single bit in C/C++?

set and clear the bits

Bitwise Operators mainly use in low-level programming and using the bit-wise operators we can set, check, clear or toggle the bits of an integral type. In the embedded system, a bit-wise operator performs the bit-wise operation on an individual bit of a PORT or Register.

Note: Quiz on bit-wise operators.

Note: Here I assume that bit of register starts with 0th position, it means the 2nd position is actually 3rd bits.


Setting a Bit

Bitwise OR operator (|) use to set a bit of integral data type.”OR” of two bits is always one if any one of them is one.

Algorithm to set the bits


Simple program to set a bit in C





Clearing a Bit

Bitwise AND operator (&) use to clear a bit of integral data type. “AND” of two bits is always zero if any one of them is zero.

Algorithm to clear the bit

To clear the nth bit, first, you need to invert the string of bits then AND it with the number.

Simple program to clear a bit


clear the bits


Checking a Bit

To check the nth bit, shift the ‘1’ nth position toward the left and then “AND” it with the number.

An algorithm to check the bit


Simple program to check a bit

OutPut 1:

Bit check

OutPut 2:

bit check


If you want to learn more about the c language, here 10 Free days  C video course for you.


Toggling a Bit

Bitwise XOR (^) operator use to toggle the bit of an integral data type. To toggle the nth bit shift the ‘1’ nth position toward the left and “XOR” it.

An algorithm to toggle the bits


Simple program to toggle a bit

OutPut 1:

toggle bit

OutPut 2:

Bit toggle


You can see this article, Interview questions on bitwise operators 

Your opinion matters

Although here I have tried to puts a lot of points regarding the bit operators but I want to know your opinion on the binary operators, so please don’t forget to write a comment in the comment box.



Leave a Reply