Code:
#include <stdio.h>
#include "util.h" /* for bits_uint */
int bitMask_(int highbit, int lowbit);
/*******************************************************************************
* 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: ! ~ & ^ | + << >>
* Max ops: 16
* Rating: 3
*/
int bitMask(int highbit, int lowbit)
{
return (((~0 << lowbit) ^ ((~0 << highbit) << 1)) >> lowbit) << lowbit;
}
int main(void)
{
int i = 5, j = 3;
printf("bitmask(%d,%d) = %x\n", i, j, bitMask_(i,j));
i = 3, j = 5;
printf("bitmask(%d,%d) = %x\n", i, j, bitMask_(i,j));
return 0;
}
/*******************************************************************************
* Program Output
bitMask_(5,3) : a = 11111111111111111111111111111000
bitMask_(5,3) : b = 11111111111111111111111111000000
bitMask_(5,3) : c = 00000000000000000000000000111000
bitMask_(5,3) : d = 00000000000000000000000000000111
bitMask_(5,3) : e = 00000000000000000000000000111000
bitmask(5,3) = 38
bitMask_(3,5) : a = 11111111111111111111111111100000
bitMask_(3,5) : b = 11111111111111111111111111110000
bitMask_(3,5) : c = 00000000000000000000000000010000
bitMask_(3,5) : d = 00000000000000000000000000000000
bitMask_(3,5) : e = 00000000000000000000000000000000
bitmask(3,5) = 0
*/
/*******************************************************************************
* Description:
* This function explains the other version "in slow motion".
* It uses the bits_uint function, implemented elsewhere, to show the bits.
*/
int bitMask_(int highbit, int lowbit)
{
char binary[33];
int a,b,c,d,e;
a = ~0 << lowbit;
printf("bitMask_(%d,%d) : a = %s\n", highbit, lowbit, bits_uint(binary, a));
b = (~0 << highbit) << 1;
printf("bitMask_(%d,%d) : b = %s\n", highbit, lowbit, bits_uint(binary, b));
c = a ^ b;
printf("bitMask_(%d,%d) : c = %s\n", highbit, lowbit, bits_uint(binary, c));
d = c >> lowbit;
printf("bitMask_(%d,%d) : d = %s\n", highbit, lowbit, bits_uint(binary, d));
e = d << lowbit;
printf("bitMask_(%d,%d) : e = %s\n", highbit, lowbit, bits_uint(binary, e));
return e;
}