Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 612
noufal Avatar asked Jun 01 '13 02:06

noufal


1 Answers

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.

like image 56
Sergey Kalinichenko Avatar answered Nov 15 '22 09:11

Sergey Kalinichenko