Search code examples
cbitwise-operators

How to get position of right most set bit in C


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 of a. Can anyone tell me how can I do so.

NOTE : I want position only, here I don't want to set or reset the bit. So it is not duplicate of any question on stackoverflow.


Solution

  • Try this

    int set_bit = n ^ (n&(n-1));
    

    Explanation:
    As noted in this answer, n&(n-1) unsets the last set bit.
    So, if we unset the last set bit and xor it with the number; by the nature of the xor operation, the last set bit will become 1 and the rest of the bits will return 0