Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the bit removed from the bitwise right shift in c#

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

like image 747
user853710 Avatar asked Jun 03 '13 13:06

user853710


People also ask

How do you shift right bits?

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.

How do I toggle a bit in embedded C?

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.

What is << in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

How do I turn off a particular bit in a number?

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.


2 Answers

(x & 1) gives you the value of the least significant bit. You should calculate it before you shift.

like image 70
Mark Byers Avatar answered Sep 20 '22 01:09

Mark Byers


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;
    }
like image 32
Mehmet Ataş Avatar answered Sep 22 '22 01:09

Mehmet Ataş