简体   繁体   中英

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

(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;
    }

Just test the first bit before removing it

int b = x & 1;

See MSDN reference on & operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM