How to turn off a particular bit in a number? | GeeksforGeeks
Given a number n and a value k, turn off the k’th bit in n.
Given a number n and a value k, turn off the k’th bit in n.
Using expression "~(1 << (k - 1))“, we get a number which has all bits set, except the k’th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k’th bit which is 0.
int
turnOffK(
int
n,
int
k)
{
// k must be greater than 0
//
if
(k <= 0)
return
n;
// Do & of n with a number with all set bits except
// the k'th bit
return
(n & ~(1 << (k - 1)));
}
It should work for negative number. Negative numbers are also represented in binary. And then any bit can be turned off.
But there are different ways to define negative number in binary e.g.
Sign and magnitude
Ones' complement
Two's complement
Read full article from How to turn off a particular bit in a number? | GeeksforGeeksSign and magnitude
Ones' complement
Two's complement