BigInteger.intValue()>1 给出了错误的布尔值
BigInteger.intValue()>1 giving incorrect boolean
我正在尝试将 BigInteger 数字转换为二进制。我使用 while 循环减少 BigInteger 直到它等于 1,在循环运行时取余数。
循环的条件是:(decimalNum.intValue()>1)。
但是程序只进行了一次循环,然后认为 BigInteger 是 less/equal 到 1,而实际上它是 55193474935748 左右。
为什么会这样?
("inBinary" 是一个 ArrayList,用于保存循环中的余数。)
这是 while 循环:
while (decimalNum.intValue()>1){
inBinary.add(0, decimalNum.mod(new BigInteger("2")).intValue()); //Get remainder (0 or 1)
decimalNum = decimalNum.divide(new BigInteger("2")); //Reduce decimalNum
}
要获取 BigInteger
的二进制字符串值,您只需执行
bigInteger.toString(2);
EDIT :正如@VinceEmigh 的评论中提到的那样,将 BigInteger
转换为 int
可能会导致溢出。
55,193,474,935,748 不适合 int:最大的 int 值是 231 - 1,即 2,147,483,647,它要小得多。所以你得到一个整数溢出。
这在 the javadoc 中有解释,顺便说一句:
Converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
如果要将 BigInteger 与 1 进行比较,请使用
decimalNum.compareTo(BigInteger.ONE) > 0
我正在尝试将 BigInteger 数字转换为二进制。我使用 while 循环减少 BigInteger 直到它等于 1,在循环运行时取余数。
循环的条件是:(decimalNum.intValue()>1)。
但是程序只进行了一次循环,然后认为 BigInteger 是 less/equal 到 1,而实际上它是 55193474935748 左右。 为什么会这样?
("inBinary" 是一个 ArrayList,用于保存循环中的余数。)
这是 while 循环:
while (decimalNum.intValue()>1){
inBinary.add(0, decimalNum.mod(new BigInteger("2")).intValue()); //Get remainder (0 or 1)
decimalNum = decimalNum.divide(new BigInteger("2")); //Reduce decimalNum
}
要获取 BigInteger
的二进制字符串值,您只需执行
bigInteger.toString(2);
EDIT :正如@VinceEmigh 的评论中提到的那样,将 BigInteger
转换为 int
可能会导致溢出。
55,193,474,935,748 不适合 int:最大的 int 值是 231 - 1,即 2,147,483,647,它要小得多。所以你得到一个整数溢出。
这在 the javadoc 中有解释,顺便说一句:
Converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
如果要将 BigInteger 与 1 进行比较,请使用
decimalNum.compareTo(BigInteger.ONE) > 0