英文:
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("foo")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论