使用 Int64() 转换后,由于整数溢出,负的 big.Int 变为正值

问题描述 投票:0回答:1

我有一个简单的 if 语句来比较两个数字。由于编译错误,我无法使用

big.Int
与零进行比较,因此我尝试转换为 int64 和 float32。问题是,在调用
Int64
float32(diff.Int64())
后,
diff
被转换为正数,我怀疑这是整数溢出的结果。

准备

diff
变量以与零进行比较的安全方法是什么?

package main
import (
    "fmt"
    "math/big"
)

func main() {
    var amount1 = &big.Int{}
    var amount2 = &big.Int{}
    amount1.SetString("465673065724131968098", 10)
    amount2.SetString("500000000000000000000", 10)

    diff := big.NewInt(0).Sub(amount1, amount2)
    fmt.Println(diff)
    // -34326934275868031902 << this is the correct number which should be compared to 0

    fmt.Println(diff.Int64())
    // 2566553871551071330 << this is what the if statement compares to 0
    if diff.Int64() > 0 {
       fmt.Println(float64(diff.Int64()), "is bigger than 0")
    }

}
go math comparison bigint
1个回答
2
投票

使用

Int.Cmp()
将其与另一个
big.Int
值进行比较,其中一个代表
0

例如:

zero := new(big.Int)

switch result := diff.Cmp(zero); result {
case -1:
    fmt.Println(diff, "is less than", zero)
case 0:
    fmt.Println(diff, "is", zero)
case 1:
    fmt.Println(diff, "is greater than", zero)
}

这将输出:

-34326934275868031902 is less than 0

与特殊的

0
进行比较时,您也可以使用
Int.Sign()
,它根据与
0
的比较结果返回 -1、0、+1。

switch sign := diff.Sign(); sign {
case -1:
    fmt.Println(diff, "is negative")
case 0:
    fmt.Println(diff, "is 0")
case 1:
    fmt.Println(diff, "is positive")
}

这将输出:

-34326934275868031902 is negative

尝试 Go Playground 上的示例。

查看相关:

还有另一种方法来测试big.Int是否为0吗?

© www.soinside.com 2019 - 2024. All rights reserved.