LargeInteger等于BigInteger的testBit吗? [英] LargeInteger's equivalent of BigInteger's testBit?
问题描述
LargeInteger
是否具有与 BigInteger
的testBit
?
如果没有,如何在LargeInteger
上执行testBit
?
If not, how can testBit
be performed on a LargeInteger
?
我还没有复制((this & (1<<n)) != 0)
的必要技能.
I don't yet have the necessary skills to reproduce ((this & (1<<n)) != 0)
.
我尝试通过仅复制& ;;粘贴文档中引用的上述代码:
I tried making a method by just copying & pasting the above code referenced from the docs:
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的情况下,这是我能提供的最好的解决方案:
This is the best I can come up with given the API:
static boolean testBit(LargeInteger i, int n) {
return i.shiftRight(n).isOdd();
}
n
是要测试的位的位置.
n
is the position of the bit to be tested.
我假设您将此方法放在某个实用程序类中.
I assume you put this method in some utility class.
通常,您将执行num & (1 << pos)
提取pos
位置的位:
Normally, you would do num & (1 << pos)
to extract the bit at pos
position:
???????x?????
0000000100000
-------------
0000000x00000
如果整个事物为0,则x
为0;如果整个事物为0,则x
为0.否则,x
为1.
If the whole thing is 0 then x
is 0; otherwise, x
is 1.
在上述方法中,我执行num >> pos
:
In the method above, I do num >> pos
:
???????x?????
-------------
????????????x
我们知道二进制数的最低有效位为1时为奇数,而最低有效位为0时则为偶数.
We know that a binary number is odd when its least significant bit is 1, and it is even when its least significant bit is 0.
因此,如果右移后的数字为奇数,则我们知道该位为1;即使是偶数,我们也知道该位为0.
So if the number after right-shifting is odd, we know the bit is 1; if even, we know the bit is 0.
这篇关于LargeInteger等于BigInteger的testBit吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!