I'm new at programming. Recently i came across a problem in which i have to make a particular bit 0 of a number.
For example :
I have a number p
p = 73
binary = 1001001
Now i want to make 4th bit to 0, that is 1000001(2) = 65(10)
I did this in following way :
int p = 73;
int pos = 1<<3; // 4th bit
int max_bit = (1<<31) - 1; // making all bit to 1
int mask = pos ^ max_bit; // making 4th bit to 0 except others
p = p & mask; // changing 4th bit of p to 0
cout<<p<<endl;
Is there a better way to do this ?
Just use : p = p & ~(1u<<3); What happens here ? That's how the bit changes to 0.
Setting a bit Use the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.
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.
Clearing 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.
Just use :
p = p & ~(1u<<3);
What happens here ?
1. (1u<<3) 0...01000
2. ~(1u<<3) 1...10111 // Invert the bits
3. p & ~(1u<<3) *****0*** // Here * means the bit representation of p
That's how the bit changes to 0.
Hope it helps :)
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