UNDERSTANDING how to count trailing zeros for a number using bitwise operators in C

后端 未结 3 595
迷失自我
迷失自我 2020-12-22 13:52

Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question

3条回答
  •  长情又很酷
    2020-12-22 14:19

    This code (from the net) is mostly C, although v &= -signed(v); isn't correct C. The intent is for it to behave as v &= ~v + 1;

    First, if v is zero, then it remains zero after the & operation, and all of the if statements are skipped, so you get 32.

    Otherwise, the & operation (when corrected) clears all bits to the left of the rightmost 1, so at that point v contains a single 1 bit. Then c is decremented to 31, i.e. all 1 bits within the possible result range.

    The if statements then determine its numeric position one bit at a time (one bit of the position number, not of v), clearing the bits that should be 0.

提交回复
热议问题