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, type .clear or toggle the bits of an integral type.In the embedded system, bit-wise operator mainly use to perform 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 start with 0th position, it means 2nd position is actually 3rd bits .

D7D6D5D4D3D2D1D0

Setting a Bits

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

Number  | =  (1<< nth Position)

Simple program to set a bit.

OutPut:

BitSet

Clearing a Bits

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 bits

Number  &=  ~ (1<< nth Position)
To clear the nth bit, first you need to invert the string of bits then AND it with number.

Simple program to clear a bit

OutPut:

clear the bits

Checking a Bits

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 bits

 Bit = Number & (1 << nth)

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 (up to 200 minutes) C video course for you.

 

Toggling a Bits

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

Number  ^=  (1<< nth Position)

Simple program to toggle a bit

OutPut 1:

toggle bit

OutPut 2:

Bit toggle

 

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.

 

3 comments

Leave a Reply