noufal
noufal

Reputation: 970

Generating particular bit pattern using bitwise operators

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 ?

Upvotes: 5

Views: 1324

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

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.

Upvotes: 5

Related Questions