big.Int 不等于 big.setBytes(bigint.Bytes()) 之后收到的一个

big.Int not equal to one received after big.setBytes(bigint.Bytes())

我想将 big int 转换为 bytes,再将 bytes 转换回 big int,然后比较这两个值。我正在使用如下类似的代码进行操作:

package main

import "fmt"
import "math/big"

func main() {
    input := "37107287533902102798797998220837590246510135740250"
    a := big.NewInt(0)
    a.SetString(input, 10)
    fmt.Println("number =", a)

    z := a.Bytes()
    b := big.NewInt(0)
    b.SetBytes(z)

    fmt.Println("number =", b)

    if a!=b{
        fmt.Println("foo")
    }

}

输出为:

number = 37107287533902102798797998220837590246510135740250
number = 37107287533902102798797998220837590246510135740250
foo

这很奇怪,数字看起来相等。 if 循环中的代码不应该被执行。 我在这里错过了什么?

您正在比较 pointers to the big.Int values, and not the internal big.Int values. Comparing big.Int values must be done using the Int.Cmp method:

func (x *Int) Cmp(y *Int) (r int)

Cmp compares x and y and returns:

-1 if x <  y
0 if x == y
+1 if x >  y
if a.Cmp(b) != 0 {
    fmt.Println("foo")
}