简体   繁体   English

使用按位运算符生成特定的位模式

[英]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 . 在这里,我想生成一个位模式,从位置p开始设置n位等于1数字。 Digits are numbered from 0 to 31 . 数字从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 ; 要使n在零位置为1,请计算(2^n)-1 recall that 2^n is 1<<n , so the expression becomes ((1<<n)-1) . 回想2^n1<<n ,因此表达式变为((1<<n)-1) Now you need to add p zeros at the back, so shift the result left by p . 现在您需要在后面添加p零,因此将结果向左移动p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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