big.Int在big.setBytes(bigint.Bytes())之后接收到的不是等于1的值。

huangapple go评论80阅读模式
英文:

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

问题

我想将一个大整数转换为字节,然后再将字节转换回大整数,然后比较这两个值。我正在使用类似下面的代码进行操作:

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循环内的代码不应该被执行。我在这里漏掉了什么?

英文:

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?

答案1

得分: 13

你正在比较指向big.Int值的指针,而不是内部的big.Int值。比较big.Int值应该使用Int.Cmp方法进行:

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

Cmp方法比较x和y,并返回:

  • 如果x < y,则返回-1
  • 如果x == y,则返回0
  • 如果x > y,则返回+1

如果a.Cmp(b) != 0,则打印"foo"。

请注意,这是代码示例,我只翻译了其中的内容。

英文:

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(&quot;foo&quot;)
}

huangapple
  • 本文由 发表于 2017年6月22日 18:32:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/44696881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定