2.68 Lower One Mask

★★

Problem:

Write code for a function with the following prototype:

/*
 * Mask with least significant n bits set to 1
 * Examples: n = 6 --> 0x3F, n = 17 --> 0x1FFFF
 * Assume 1 <= n <= w
 */
int lower_one_mask(int n);

Be careful of the case n=w.

Code:

#include <stdio.h>
#include <assert.h>

int lower_one_mask(int n) {
    int w = sizeof(int) << 3;
    return (unsigned)-1 >> (w - n);
}

int main() {
    assert(lower_one_mask(6)==0x3F);
    assert(lower_one_mask(17)==0x1FFFF);
    assert(lower_one_mask(32)==0xFFFFFFFF);
}

Last updated