简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM