java - LargeInteger 相当于 BigInteger 的 testBit?

标签 java biginteger jscience

是否 LargeInteger 相当于 BigInteger 's testBit

如果不是,怎么可能testBitLargeInteger 上执行?

我还没有必要的技能来复制((this & (1<<n)) != 0) .


我尝试通过复制和粘贴从文档中引用的上述代码来创建一个方法:

static boolean testBit(int n){
    return ((this & (1<<n)) != 0);
}

但是,编译器报告:

error: non-static variable this cannot be referenced from a static context
    return ((this & (1<<n)) != 0);
             ^
error: bad operand types for binary operator '&'
    return ((this & (1<<n)) != 0);
                  ^

最佳答案

这是我能想到的最好的 API:

static boolean testBit(LargeInteger i, int n) {
    return i.shiftRight(n).isOdd();
}

n是待测位的位置。

我假设您将此方法放在某个实用程序类中。

解释

通常,你会做 num & (1 << pos)pos 处提取位当前位置:

???????x?????
0000000100000
-------------
0000000x00000

如果整个事情是 0 那么 x为 0;否则,x为 1。


在上面的方法中,我做 num >> pos :

???????x?????
-------------
????????????x

我们知道二进制数的最低位为1时为奇数,最低位为0时为偶数。

所以如果右移后的数是奇数,我们就知道该位是1;如果偶数,我们知道该位为 0。

关于java - LargeInteger 相当于 BigInteger 的 testBit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21286794/

相关文章:

kotlin - 未解析的引用 : [BigInteger]. longValue

c++ - C++中的无限循环

java - 如何在java中将数字转换为单词

java - 打印 JScience 中所有定义的单位

java - 在 jscience 中使用惯性矩

java - 四叉树如何处理非正方形区域?

java - BigInteger.and 正在做什么

java - Hibernate session.save() 总是返回 1

java - spring应用程序的tomcat 6出现404错误

Java 打印机 API