How to get position of right most set bit in C

前端 未结 15 1964
你的背包
你的背包 2020-12-09 04:48
int a = 12;

for eg: binary of 12 is 1100 so answer should be 3 as 3rd bit from right is set.

I want the position of the last most set bit o

15条回答
  •  Happy的楠姐
    2020-12-09 05:18

    The leftmost bit of n can be obtained using the formulae: n & ~(n-1)

    This works because when you calculate (n-1) .. you are actually making all the zeros till the rightmost bit to 1, and the rightmost bit to 0. Then you take a NOT of it .. which leaves you with the following: x= ~(bits from the original number) + (rightmost 1 bit) + trailing zeros

    Now, if you do (n & x), you get what you need, as the only bit that is 1 in both n and x is the rightmost bit.

    Phewwwww .. :sweat_smile:

    http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/ helped me understand this.

提交回复
热议问题