Say, I have a integer like 10101
, I would like to unset the third bit to get 10001
; if I have 10001
, I will still get 10001
; how can I achieve it?
unset(int i, int j)
int i= 10101 or 10000
int j = 00100
The idea is to use bitwise <<, & and ~ operators. 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.
Use the bitwise AND operator (&) to clear a bit. That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it. NOTE : here x is the position of bit starting from 0 to LSB.
Logic to get nth bit of a number Store it in some variable say num. Input the bit position from user. Store it in some variable say n. To get the nth bit of num right shift num, n times.
Assuming that you are indexing bits from the right, this should work to unset a particular bit in value
:
int mask = 1 << bitIndex;
value &= ~mask;
You can set the bit using similar code:
value |= mask;
where mask
is as before. (This assumes that bit indexing starts at 0.)
To clear or unset a bit
Use the bitwise AND operator (&) to clear a bit.
number &= ~(1 << x);
That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
NOTE : here x is the position of bit starting from 0 to LSB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With