我使用 64 位整数中的位存储标志.
我想知道在 64 位整数中的位置是否设置了一个位(即我不关心任何特定位的位置).
I store flags using bits within a 64-bits integer.
I want to know if there is a single bit set whatever the position within the 64-bits integer (e.i. I do not care about the position of any specific bit).
boolean isOneSingleBitSet (long integer64)
{
return ....;
}
我可以使用 Bit Twiddling Hacks 计算位数(肖恩·埃隆·安德森(Sean Eron Anderson)),但我想知道仅检测是否设置了一个位的最有效方法是什么...
I could count number of bits using the Bit Twiddling Hacks (by Sean Eron Anderson), but I am wondering what is the most efficient way to just detect whether one single bit is set...
我发现了一些其他相关的问题:
I found some other related questions:
还有一些维基百科页面:
and also some Wikipedia pages:
注意:我的应用程序是用 java 编写的,但我对使用其他语言的优化感到好奇...
NB: my application is in java, but I am curious about optimizations using other languages...
编辑:Lu Vnh Phúc 指出我的问题中的第一个链接已经得到了答案:请参阅确定整数是否为 2 的幂部分em>Bit Twiddling Hacks(作者 Sean Eron Anderson).我没有意识到一位与二的幂是一样的.
EDIT: Lu Vnh Phúc pointed out that my first link within my question already got the answer: see section Determining if an integer is a power of 2 in the Bit Twiddling Hacks (by Sean Eron Anderson). I did not realized that one single bit was the same as power of two.
如果您只是想检查是否设置了一个位,那么您实际上是在检查该数字是否是 2 的幂.要做到这一点,您可以做:
If you just literally want to check if one single bit is set, then you are essentially checking if the number is a power of 2. To do this you can do:
if ((number & (number-1)) == 0) ...
这也将 0 视为 2 的幂,因此如果这很重要,您应该检查不是 0 的数字.那么:
This will also count 0 as a power of 2, so you should check for the number not being 0 if that is important. So then:
if (number != 0 && (number & (number-1)) == 0) ...
这篇关于检查整数中是否只设置了一个位(无论其位置如何)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!