算法生成位掩码 [英] Algorithm to generate bit mask
问题描述
我面临基于所述输入参数的位掩码的这种独特的问题。例如,
I was facing this unique problem of generating a bit-mask based on the input parameter. For example,
如果参数= 2,则遮罩将是0x3中(11B) 如果param = 5,则遮罩将是为0x1F(1 1111B)
if param = 2, then the mask will be 0x3 (11b) if param = 5, then the mask will be 0x1F (1 1111b)
这个我实现了用一个for循环中的C,像
This I implemented using a for-loop in C, something like
int nMask = 0;
for (int i = 0; i < param; i ++) {
nMask |= (1 << i);
}
我想知道是否有更好的算法~~~
I would like to know if there is a better algorithm ~~~
推荐答案
有一点要注意的一样,位掩码是,他们总是比2的幂小。
One thing to notice about bitmasks like that is that they are always one less than a power of two.
这位前pression1&LT; n种,是最简单的方式来获得2的n次方
The expression "1 << n" is the easy way to get the n-th power of two.
您不想零提供00000001的位掩码,你想让它提供零。所以,你需要减一。
You don't want Zero to provide a bitmask of "00000001", you want it to provide zero. So you need to subtract one.
mask = (1 << param) - 1;
编辑:的
如果你想为param>的32个特例:
If you want a special case for param > 32:
int sizeInBits = sizeof(mask) * BITS_PER_BYTE; // BITS_PER_BYTE = 8;
mask = (param >= sizeInBits ? -1 : (1 << param) - 1);
此方法应该为16,32,或64位整数,但您可能必须明确地键入1。
This method should work for 16, 32, or 64 bit integers, but you may have to explicitly type the '1'.
这篇关于算法生成位掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!