我可以想到三种方法来做到这一点。我会很快地概述它们。
char mask = (1<<top)
mask = mask-1
mask = mask>>bot
mask = mask<<bot
3 shifts, 1 addition
char topMask = (1<<top)
topMask = topMask -1
char botMask = (1<<bot)
botMask = botMask - 1
char mask = topMask - botMask
2 shifts, 3 additions
char mask = (1<<(top-bot))
mask = mask - 1
mask = mask << bot
2 shifts, 2 additions
好像第一个会快一点? 出于风格原因,一个被认为是最好的吗? 有没有我想念的好方法,或者我在做一些愚蠢的事情?谢谢!
如果有人能指出我在 linux 内核中完成此操作的位置,我会特别感兴趣。
编辑: 有人以另一种方式发布了类似的内容并删除了它?和第二个差不多。但是异或而不是减法。
char mask = ((1<<top)-1)^((1<<bot)-1)
最佳答案
您可以尝试使用查找表方法:
static const char LUT[][] = { // index like this LUT[bot][top]
//top: 0 1 2 3 4 5 6 7 8
0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF, // bot: 0
0x00, 0x00, 0x02, 0x06, 0x0E, 0x1E, 0x3E, 0x7E, 0xFE, // bot: 1
0x00, 0x00, 0x00, 0x04, 0x0C, 0x1C, 0x3C, 0x7C, 0xFC, // bot: 2
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x38, 0x78, 0xF8, // bot: 3
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x30, 0x70, 0xF0, // bot: 4
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x60, 0xE0, // bot: 5
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xC0, // bot: 6
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, // bot: 7
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // bot: 8
};
char mask = LUT[bot][top];
此外:如果出于某种原因您要进行位操作,则此解决方案需要的操作更少。此外,超标量处理器应该并行计算异或运算的左侧和右侧。
char mask = (0xFF << top) ^ (0xFF << bot);
关于bit-manipulation - 为一系列位创建位掩码的最佳实践方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21465833/