How to Set, Clear and toggling a particular bit in C, C++

In embedded world you may be need to set a particular bit while configuring a register, clear a bit when decoding a data and then toggle a bit in applications like external watchdog timer services. In this tutorial let us see how can we achieve this with C/C++ language.

Setting a particular bit

Bit wise OR (|) is used for setting a bit

Formula

Register_Value = Register_Value | (1<<X)
here, X is the position of the bit which you want to set.
Example
Consider a register with 1 byte of size.
It has value of 11010001, If i want to set the 2nd bit in this register
Register_Value = 11010001 | (1<<2)
Register_Value = 11010001 | 00000100
Register_Value = 11010101

Clearing a particular bit

Bit wise AND(&) is used for clearing a bit

Formula

Register_Value = Register_Value & (~(1<<X))
here, X is the position of the bit which you want to clear.
Example
Consider a register with 1 byte of size.
It has value of 11010101, If i want to set the 2nd bit in this register
Register_Value = 11010101 & (~(1<<2))
Register_Value = 11010101 & (~00000100)
Register_Value = 11010101 & 11111011
Register_Value = 11010001

Toggling a particular bit

Bit wise XOR(^) is used for toggling a bit

Formula

Register_Value = Register_Value ^ (1<<X)
here, X is the position of the bit which you want to toggle.
Example
Consider a register with 1 byte of size.
It has value of 11010101, If i want to toggle the 2nd bit in this register
Register_Value = 11010101 ^ (1<<2)
Register_Value = 11010101 ^ 000000100
Register_Value = 11010101

Also refer
How to Check a particular bit is set or not ?
How to set/clear/toggle multiple bit?

Cheers!!!!
-> Let Us Embed <-