How do you set, clear, and toggle a single bit?

Explanation

You can set, clear, and toggle a single bit by the following:

Setting a bit

To set a bit you can use the bitwise OR operator (|

number |= 1UL << n;

That will set the nth bit of number.

Clearing a bit

To clear a bit you can use the bitwise AND operator (&)  

number &= ~(1UL << n);

And this will clear the nth bit of number. 

Toggling a bit

We can toggle a single bit by using the XOR operator (^).

number ^= 1UL << n;

This will help to toggle the nth bit of number.  

 

 

Also read, How to insert an item into an array at a specific index

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *