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 ?
You can do it like this:
return ((1<<n)-1)<<p;
To make n ones at position zero, compute (2^n)-1; recall that 2^n is 1<<n, so the expression becomes ((1<<n)-1). Now you need to add p zeros at the back, so shift the result left by p.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With