bit manipulation: clearing range of bits

前端 未结 4 1006
鱼传尺愫
鱼传尺愫 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:07

    let's assume i= 5

    (1 << i) give you 0100000 the 1 is placed in the 6th bit position

    so now if we substract 1 from it, then we get 0011111 ==> only the 5 first bit are set to 1 and others are set to 0 and that's how we get our mask

    Conclusion: for a giving i the (1 << i) -1 will give you a mask with the i first bits set to 1 and others set to 0

提交回复
热议问题