5

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 ?

3
  • 2
    You're invoking undefined behaviour when 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? Commented Jun 1, 2013 at 2:11
  • @DanielFischer in my problem (n+p) won't go beyond 31. and it is easy to identify too... Commented Jun 1, 2013 at 2:15
  • 1
    Anyway, if you only care about the bits, I'd recommend using an unsigned type, and then ((1 << n) - 1) << p is safe unless n or p are negative or greater than or equal to the width of the type. Commented Jun 1, 2013 at 2:18

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.