douxi0098 2017-06-22 10:32
浏览 639
已采纳

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

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条回答 默认 最新

  • dongye1934 2017-06-22 10:41
    关注

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑