I had a problem writing the following function:
/*
* 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
*/
I wrote this so far:
I know it is very poor code and it doesn't seem to work when the low bit is 0 and/or high bit is 31 among other cases. Try as I might, I can't seem to be able to fix this problem. I think I'm going about this problem wrong. I know a lot of you guys are pros here so if you could point me in the right direction, many thanks to you! :)Code:int bitMask(int highbit, int lowbit) {
int PosOrNeg = highbit+(~lowbit+1);
int sign = PosOrNeg >> 31;
int endXOR = sign ^ ~0;
int ANDwith = ~(0x1 << 31);
int rshift = 32 + (~highbit + 1);
ANDwith = ANDwith >> rshift;
ANDwith = ANDwith << lowbit;
endXOR = endXOR & ANDwith;
int num= 0 ^ endXOR;
return num;
}