Which bitwise operator is suitable for turning OFF a perticular bit in a number

28 Dec 2022 Balmiki Kumar 0 C Programming

Turning Off a Specific Bit in a Number in C using Bitwise Operators

To turn off a particular bit in a number, the suitable bitwise operator to use is the bitwise AND operator (&).

The bitwise AND operator works by setting each bit of the result to 1 only if the corresponding bits of both operands are 1. If any of the corresponding bits are 0, the result bit is set to 0. By using a bitwise AND with a number that has a 0 bit in the position we want to turn off, we can set that bit to 0 in the original number.

Here's an example in C code that turns off the third bit (counting from the right) of a variable x:

x = x & ~(1 << 2);

In this example, the expression 1 << 2 creates a value with a 1 in the third bit position (2 because we are counting from 0), and the bitwise NOT operator (~) is used to invert all the bits in this value so that it has a 0 in the third bit position and 1s elsewhere. Finally, the bitwise AND operator is used to mask off the third bit of x by setting it to 0 while leaving all other bits unchanged.

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.