I want to convert a big int to bytes and the bytes back to big int and then compare the two values. I am doing it using similar code as below:
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")
}
}
The output is:
number = 37107287533902102798797998220837590246510135740250
number = 37107287533902102798797998220837590246510135740250
foo
This is strange, the numbers look equal. The code inside if loop should not be executed. What am I missing here?
You are comparing the 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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With