Java BigInteger testBit 64位长

时间:2015-01-22 09:31:32

标签: java binary long-integer biginteger

这可能是一个愚蠢的问题,但我似乎无法找到一个简单的答案。

我正在读取64位(8字节)long值,然后我尝试使用BigInteger.testBit查看是否设置了第63位,因为它& #39;被用作旗帜。

long value = 0x4000863; //This value is actually read from a file
Long.toBinaryString(value) = 100000000000000100001100011
BigInteger test = new BigInteger(Long.toString(value));
if (test.testBit(63)) {
    //yay
}
else {
    //boo
}

以上代码是我目前正在尝试的代码,它表示第63位未设置。由于它被存储了很长时间,我不认为我必须填补价值,或者我只是完全做错了什么?

非常感谢任何意见或建议。

感谢。

1 个答案:

答案 0 :(得分:3)

你正在计算错误的位数:

public void test() {
    // Binary - 100000000000000100001100011
    //          ^ This is bit 26
    long value = 0x4000863; 
    // Binary - ‭1000000000000000000000000000000000000000000000000000000000000000‬
    //          ^ THIS is bit 63
    long bigger = 0x8000000000000000L;
    BigInteger test = new BigInteger(Long.toString(value));
    System.out.println("L:" + Long.toBinaryString(value) + "\r\nB:" + test.toString(2) + "\r\nB63:" + test.testBit(63));
    test = new BigInteger(Long.toString(bigger));
    System.out.println("L:" + Long.toBinaryString(bigger) + "\r\nB:" + test.toString(2) + "\r\nB63:" + test.testBit(63));
}