本文介绍了检查是否只有一个位整数中设置(无论其位置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我店使用的是64位整数位之内的标志。结果
我想知道,如果有一个位设置到任何64位整数中的位置(E.I.我不关心任何特定的位的位置)。

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 ....;
}

我可以使用数位数量的,但我想知道什么是只检测一个单个位是否设置最有效的方式...

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:



  • (8051) Check if a single bit is set
  • Detecting single one-bit streams within an integer

,也有一些维基百科页面:

and also some Wikipedia pages:





  • Find first one
  • Bit manipulation
  • Hamming weight

注:我的应用程序是在Java中,但我使用其他语言很好奇优化...

NB: my application is in java, but I am curious about optimizations using other languages...

修改:指出我的问题在我的第一个环节已经得到了答案:参见中的位操作黑客的(由肖恩·安德森玉龙)。我没有意识到的单个位是一样的两个电源

EDIT: Lưu Vĩnh 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) ...

这篇关于检查是否只有一个位整数中设置(无论其位置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:10
查看更多