Skip to main content

Sponsors

Generating Bit Mask in C

Posted in

Given a number n, I want to generate n number of 1s on the less significant bits. For example, when n is 3, bit mask = 0000 0000 0000 01112. Observe that the bit mask is equivalent to 2n-1. The following codes try to generate the bit mask.

// Note that *long* is 64bit in this case, running on a 64bit Linux OS.
int i;
for (i = 1; i <= 64; i++) {
        printf("method 1: mask %d: %lx\n", i, (1UL << i)-1); // 2^n-1
        printf("method 2: mask %d: %lx\n", i, ~(~0UL << i));
        printf("method 3: mask %d: %lx\n", i, ~0UL >> (-i)); // obscure.
        printf("method 4: mask %d: %lx\n", i, ~0UL >> (64-i));
        printf("method 5: mask %d: %lx\n", i, ~((~0UL-1UL) << (i-1)));
        printf("\n");
}

However, method 1 and method 2 do not work when n is 64. Both of these methods suffer from shift overflow. When it shifts to the left by 64, the shift operator simply refuse to work, and return the original value.

Method 3 is surprisingly working correctly in my environment. Further study indicates that -i is converted to unsigned (large number), and applied mod 64 before the shift. It becomes equivalent to method 4. However, method 3 is not guaranteed to work with all standard compilers. Note that you can't shift by a negative constant e.g. –2.

Method 5 is just a longer way, start with 1111…10 bit pattern and shift left by n-1, then complement.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.