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.
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
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
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 <-
Setting a particular bit
Bit wise OR (|) is used for setting a bitFormula
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 bitFormula
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 bitFormula
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 <-