[英]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^n
为1<<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.