bit manipulation: clearing range of bits

前端 未结 4 1009
鱼传尺愫
鱼传尺愫 2020-12-29 10:58

I\'m preparing for an interview using the text, \"Cracking the Coding Interview\" by Gayle Laakman McDowell. On the section covering bit manipulation, there are two function

4条回答
  •  庸人自扰
    2020-12-29 11:05

    For the first question:

    lets say i = 5

    (1 << i )    = 0010 0000 = 32 in base 10
    (1 << i ) -1 = 0001 1111 = 31 
    

    So a & with this mask clears the most significant bit down to i because all bit positions above and including index i will be 0 and any bellow will be 1.

    For the second question:

    Again lets say i = 5

      (1 << (i + 1))      = 0100 0000 = 64 in base 10
      (1 << (i + 1)) - 1  = 0011 1111 = 63
    ~((1 << (i + 1)) - 1) = 1100 0000 = 192
    

    So a & with this masks clears bits up to index i

提交回复
热议问题