检查字节中第 n 位是否已设置的函数
我想要一个简单的 C 函数,如果字节中的第 n 位设置为1
,它将返回 true。否则会返回 false。
就执行时间而言,这是一个关键函数,因此我正在考虑执行此操作的最佳方法。
I want a simple C function which will return true if the n-th bit in a byte is set to1
. Otherwise it will return false.
This is a critical function in terms of execution time, so I am thinking of the most optimal way to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
以下函数可以满足您的需要:
这里假设 8 位字节(C 中未给定),并且第 0 位是最高位。如果这些假设不正确,则只需扩展和/或重新排序
mask
数组即可。由于您将速度作为最重要的考虑因素,因此没有进行错误检查。不要传入无效的
n
,这将是未定义的行为。在疯狂的优化级别
-O3
上,gcc 为我们提供:非常小且高效。如果您将其设为静态并建议内联,或强制将其作为宏定义内联,您甚至可以绕过函数调用的成本。
只需确保对您提供的任何解决方案进行基准测试,包括这个(a)。优化中的首要原则是“测量,不要猜测!”
如果您想了解按位运算符的工作原理,请参阅此处。简化的仅 AND 版本如下。
仅当在两个源中都设置了两个位时,AND 运算
&
才会在目标中设置一个位。相关表格为:对于给定的 char 值,我们使用单位位掩码来检查是否设置了某个位。假设您的值为 13,并且您想查看是否设置了从最低有效位起第三位。
您可以看到掩码中的所有零位都会导致等效结果位为零。掩码中的单个一位基本上会让值中的等效位流过结果。如果我们检查的位为零,则结果为零;如果为 1,则结果非零。
这就是
return
语句中的表达式的来源。mask
查找表中的值都是单位掩码:(a) 我知道我有多好,但你不知道:-)
The following function can do what you need:
This assumes 8-bit bytes (not a given in C) and the zeroth bit being the highest order one. If those assumption are incorrect, it simply comes down to expanding and/or re-ordering the
mask
array.No error checking is done since you cited speed as the most important consideration. Do not pass in an invalid
n
, that'll be undefined behaviour.At insane optimisation level
-O3
, gcc gives us:which is pretty small and efficient. And if you make it static and suggest inlining, or force it inline as a macro definition, you can even bypass the cost of a function call.
Just make sure you benchmark any solution you're given, including this one (a). The number one mantra in optimisation is "Measure, don't guess!"
If you want to know how the bitwise operators work, see here. The simplified AND-only version is below.
The AND operation
&
will set a bit in the target only if both bits are set in the tewo sources. The relevant table is:For a given
char
value, we use the single-bit bit masks to check if a bit is set. Let's say you have the value 13 and you want to see if the third-from-least-significant bit is set.You can see that all the zero bits in the mask result in the equivalent result bits being zero. The single one bit in the mask will basically let the equivalent bit in the value flow through to the result. The result is then zero if the bit we're checking was zero, or non-zero if it was one.
That's where the expression in the
return
statement comes from. The values in themask
lookup table are all the single-bit masks:(a) I know how good I am, but you don't :-)
只需检查
(1 << bit) & 的值即可字节
。如果它非零,则该位被设置。Just check the value of
(1 << bit) & byte
. If it is nonzero, the bit is set.令数字为
num
。然后:Let the number be
num
. Then:另一种方法是
Another approach would be