cbitwise-operatorsbitbit-shiftbit-masks

Can someone explain how this bitMask code works?


This is code that my partner came up with but for some reason I can't get a hold of him to ask him how it's suppose to work. I've been through it many times now and can't seem to get the answer I'm suppose to get.

/**
 * bitMask - Generate a mask consisting of all 1's 
 *   lowbit and highbit
 *   Examples: bitMask(5,3) = 0x38
 *   Assume 0 <= lowbit <= 31, and 0 <= highbit <= 31
 *   If lowbit > highbit, then mask should be all 0's
 *   Legal ops: ! ~ & ^ | + << >>
 */
int bitMask(int highbit, int lowbit) {
   int i = ~0;
   return ~(i << highbit << 1) & (i << lowbit);
}

Solution

  • This function is actually incorrect: for large values of highbit and lowbit, it may have implementation specific behavior or even undefined behavior. It should use and return unsigned types:

    unsigned bitMask(int highbit, int lowbit) {
        unsigned i = ~0U;
        return ~(i << highbit << 1) & (i << lowbit);
    }
    

    Here are the steps:

    examples:

    This numbering method is used in hardware specifications. I personally prefer a different method where one specifies the number of bits to skip and the number of bits to set, more consistent with bit-field specifications:

    unsigned bitSpec(int start, int len) {
        return (~0U >> (32 - len)) << start;
    }
    

    and the same examples: