为一系列位创建位掩码的最佳实践是什么? [英] What is the best practice way to create a bitmask for a range of bits?

查看:54
本文介绍了为一系列位创建位掩码的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以想到三种方法来解决这个问题.我很快就会概述它们.

I can think of three ways to do this off the top of my head. I'll outline them real quick.

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

似乎第一个会快一点? 出于风格原因,是否被认为是最好的选择? 我是否真的有一个很好的方法,或者我正在做一些愚蠢的事情?谢谢!

It seems like the first one would be a little faster? Is one considered best for style reasons? Is there a really good way I'm missing, or am I doing something stupid? Thanks!

如果有人能指出我在Linux内核中所做的工作,我将特别感兴趣.

I'd especially be interested if anyone could point me to a place this is done in the linux kernel.

有人以另一种方式发布了这样的内容并删除了它?与第二个非常相似.但是XOR而不是减法.

someone posted something like this as another way and deleted it? Pretty similar to the second one. But XOR instead of subtract.

char mask = ((1<<top)-1)^((1<<bot)-1)

推荐答案

您可以尝试使用查找表方法:

You could try a lookup table approach:

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];

也:如果出于任何原因而进行位操作,则此解决方案所需的操作较少.另外,超标量处理器应并行评估异或的左侧和右侧.

Also: If for whatever reason you go with bit manipulation this solution requires less ops. In addition a superscalar processor should evaluate the left and right side of the xor in parallel.

char mask = (0xFF << top) ^ (0xFF << bot);

这篇关于为一系列位创建位掩码的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆