为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕森王 2023-01-03 11:27:24
我有一个比较两个数字的简单 if 语句。由于编译错误,我无法使用big.Int与零进行比较,因此我尝试转换为 int64 和 float32。问题是在调用Int64or之后float32(diff.Int64()),diff被转换为一个正数,我怀疑这是整数溢出的结果。如果有人能告诉我什么是准备diff与零比较的变量的安全方法,我将不胜感激。package mainimport (    "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")    }}
查看完整描述

1 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

用于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()它返回 -1、0、+1,具体取决于与 的比较结果0。


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 的方法吗?


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信