6

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

user853710
  • 1,715
  • 1
  • 13
  • 27

3 Answers3

7

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

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

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;
    }
Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78
1

Just test the first bit before removing it

int b = x & 1;

See MSDN reference on & operator

Steve
  • 213,761
  • 22
  • 232
  • 286