检查整数中是否只设置了一个位(无论其位置如何)

Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
本文介绍了检查整数中是否只设置了一个位(无论其位置如何)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我使用 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:

  • (8051) 检查是否设置了单个位
  • 检测整数内的单个一位流

还有一些维基百科页面:

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) ...

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)