这个问题在这里已经有了答案:
Find out number of bits needed to represent a positive integer in binary?
(14 个回答)
3年前关闭。
如何获得整数中最高一位的位置而不是值?我知道我可以得到这样的值(value):
// Prints 8; in 1101, the highest bit is the one denoting 8
int f = 13;
System.out.println("Highest: " + Integer.highestOneBit(f));
但是,我想获得最高一位的位置 - 在这种情况下,它将是 4(因为
1000
二进制 == 8
,最高一位是第四位)。
最佳答案
好吧,我们可以在数学上做到这一点。
我们基本上想从 8 中得到 4,从 4 中得到 3,从 2 中得到 2,从 1 中得到 1,等等。
这基本上是对数字进行 log2 并将其加 1。没有log2
java.lang.Math
中的函数类,但您可能知道:
logx(y) = log10(y) / log10(x)
所以我们可以这样做!
(Math.log10(Integer.highestOneBit(f)) / Math.log10(2)) + 1
关于java - 获取位置而不是整数中最高一位的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754061/