I have a int number And I have to shift it to the right a couple of times.
x = 27 = 11011
x>>1= 13 = 1101
x>>2= 6 = 110
x>>3= 3 = 11
I would like to get the value bit value that has been removed. I would have to get: 1, 1, 0
How can I get the removed value
When shifting right with a logical right shift, the least-significant bit is lost and a 0 is inserted on the other end. For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.
Toggle a bit Since XOR of unset and set bit results in a set bit and XOR of a set and set bit results in an unset bit. Hence performing bitwise XOR of any bit with a set bit results in toggle of that bit, i.e. So in order to toggle a bit, performing a bitwise XOR of the number with a reset bit is the best idea.
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
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.
(x & 1)
gives you the value of the least significant bit. You should calculate it before you shift.
For least significant bit you can use x & 1
before each shifting. If you want to get a custom bit at any time without changing the value, you can use below method.
private static int GetNthBit(int x, int n)
{
return (x >> n) & 1;
}
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