How to get position of right most set bit in C

前端 未结 15 1957
你的背包
你的背包 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:32

    You must check all 32 bits starting at index 0 and working your way to the left. If you can bitwise-and your a with a one bit at that position and get a non-zero value back, it means the bit is set.

    #include 
    
    int last_set_pos(int a) {
      for (int i = 0; i < sizeof a * CHAR_BIT; ++i) {
        if (a & (0x1 << i)) return i;
      }
      return -1; // a == 0
    }
    

    On typical systems int will be 32 bits, but doing sizeof a * CHAR_BIT will get you the right number of bits in a even if it's a different size

提交回复
热议问题