How to get position of right most set bit in C

前端 未结 15 1971
你的背包
你的背包 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条回答
  •  庸人自扰
    2020-12-09 05:10

    1- Subtract 1 form number: (a-1)

    2- Take it's negation : ~(a-1)

    3- Take 'AND' operation with original number:

    int last_set_bit = a & ~(a-1)

    The reason behind subtraction is, when you take negation it set its last bit 1, so when take 'AND' it gives last set bit.

提交回复
热议问题