bit manipulation: clearing range of bits

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

    // To clear all bits from the most significant bit through i (inclusive), we do:

    int clearMSBthroughI(int num, int i) {
        int mask = (1 << i) - 1;
        return num & mask;
    }
    
    Take the example of i = 3
    1<<3 gives you 0x00001000 
    (1<<3)-1 gives you 0x00000111
    num & (1<

    // To clear all bits from i through 0 (inclusive), we do:

    int clearBitsIthrough0(int num, int i) {
        int mask = ~(((1 << (i+1)) - 1);
        return num & mask;
    }
    

    same example of i = 3 gives you

    1 <<(3+1) =0x00010000
    1 <<(3+1)-1 = 0x00001111
    mask =~(1<<(3+1)-1) = 0x11110000
    num & mask will cleaR the bits from 0 throuh i
    

提交回复
热议问题