Extracting rightmost N bits of an integer

后端 未结 4 678
南方客
南方客 2021-01-01 16:16

In the yester Code Jam Qualification round http://code.google.com/codejam/contest/dashboard?c=433101#s=a&a=0 , there was a problem called Snapper Chain. From the contest

4条回答
  •  孤独总比滥情好
    2021-01-01 16:45

    Let's use N=3 as an example. In binary, 1<<3 == 0b1000. So 1<<3 - 1 == 0b111.

    In general, 1< creates a number with N ones in binary form.

    Let R = 1<. Then the expression becomes (K&R) == R. The K&R will extract the last N bits, for example:

         101001010
      &        111
      ———————————— 
         000000010
    

    (Recall that the bitwise-AND will return 1 in a digit, if and only if both operands have a 1 in that digit.)

    The equality holds if and only if the last N bits are all 1. Thus the expression checks if K ends with N ones.

提交回复
热议问题