Here I want to generate a bit pattern to set n digits equal to 1 starting from position p.
Digits are numbered from 0 to 31.
Following is what I did.
int bitPattern(int n, int p) {
int hex, num1, num2;
hex = 0x80000000;
num1 = (hex >> (31 - p));
num2 = (hex >> (31 - (n+p)));
return num1 ^ num2;
}
Example:
bitPattern(6, 2) should return
..000011111100
Any alternate solutions with less operators ?
n+p > 31. If that's guaranteed to never be the case, you still have implementation-defined behaviour right-shifting a negative number. But if you're not afraid of UB, what about((1 << n) - 1) << p?(n+p)won't go beyond 31. and it is easy to identify too...((1 << n) - 1) << pis safe unlessnorpare negative or greater than or equal to the width of the type.