【问题标题】:BigInteger.intValue()>1 giving incorrect booleanBigInteger.intValue()>1 给出不正确的布尔值
【发布时间】:2016-01-16 07:22:36
【问题描述】:

我正在尝试将 BigInteger 数转换为二进制数。我使用 while 循环来减少 BigInteger 直到它等于 1,在循环运行时取余数。

循环的条件是:(decimalNum.intValue()>1)。

但程序只循环一次,然后认为 BigInteger 小于/等于 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 值表示为int,因为int 只能达到2b。我猜intValue 溢出了

标签: java math while-loop conditional biginteger


【解决方案1】:

55,193,474,935,748 不适合 int:最大的 int 值为 231 - 1,即 2,147,483,647,它要小得多。所以你得到一个整数溢出。

这在the javadoc 中有解释,顺便说一句:

将此 BigInteger 转换为 int。此转换类似于 Java™ 语言规范的第 5.1.3 节中定义的从 long 到 int 的缩小原始转换:如果此 BigInteger 太大而无法放入 int,则仅返回低 32 位。请注意,此转换可能会丢失有关 BigInteger 值整体大小的信息,并返回带有相反符号的结果。

如果要将 BigInteger 与 1 进行比较,请使用

decimalNum.compareTo(BigInteger.ONE) > 0

【讨论】:

    【解决方案2】:

    要获取BigInteger 的二进制字符串值,您可以这样做

    bigInteger.toString(2);
    

    编辑:正如@VinceEmigh 在cmets 中提到的,将BigInteger 转换为int 可能会导致溢出。

    【讨论】:

    • 谢谢!不知道 BigInteger 有一个方法。
    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多