[英]Negative big.Int turns positive after using Int64() conversion due integer overflow
I have a simple if statement which compares two numbers.我有一个比较两个数字的简单 if 语句。 I couldn't use
big.Int
to compare with zero due to compile error, therefore I tried to convert to an int64 and to a float32.由于编译错误,我无法使用
big.Int
与零进行比较,因此我尝试转换为 int64 和 float32。 The problem is that after calling Int64
or float32(diff.Int64())
, diff
gets converted into a positive number which is a result of an integer overflow I suspect.问题是在调用
Int64
或float32(diff.Int64())
之后, diff
被转换为正数,这是我怀疑的整数溢出的结果。 I would appreciate if somebody could show me what is the safe way to prepare the diff
variable for the comparison with zero.如果有人能告诉我什么是准备
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")
}
}
Use Int.Cmp()
to compare it to another big.Int
value, one representing 0
.使用
Int.Cmp()
将其与另一个big.Int
值进行比较,一个代表0
。
For example:例如:
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)
}
This will output:这将输出:
-34326934275868031902 is less than 0
When comparing to the special 0
, instead you could also use Int.Sign()
which returns -1, 0, +1 depending on the result of the comparison to 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")
}
This will output:这将输出:
-34326934275868031902 is negative
Try the examples on the Go Playground .试试Go Playground上的示例。
See related:见相关:
Is there another way of testing if a big.Int is 0? 如果 big.Int 为 0,是否有另一种测试方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.