dongmu3457 2018-05-25 12:41 采纳率: 0%
浏览 1260

我如何将* big.Int转换为golang中的字节数组

Im trying to do calculations on a big int number and then convert the result to a byte array, but I cannot figure out how to do so this is where Im at so far. anyone got any ideas

sum := big.NewInt(0)

for _, num := range balances {
    sum = sum.Add(sum, num)
}

fmt.Println("total: ", sum)

phrase := []byte(sum)
phraseLen := len(phrase)
padNumber := 65 - phraseLen
  • 写回答

1条回答 默认 最新

  • dq1685513999 2018-05-25 13:56
    关注

    Try using Int.Bytes() to get the byte array representation and Int.SetBytes([]byte) to set the value from a byte array. For example:

    x := new(big.Int).SetInt64(123456)
    fmt.Printf("OK: x=%s (bytes=%#v)
    ", x, x.Bytes())
    // OK: x=123456 (bytes=[]byte{0x1, 0xe2, 0x40})
    
    y := new(big.Int).SetBytes(x.Bytes())
    fmt.Printf("OK: y=%s (bytes=%#v)
    ", y, y.Bytes())
    // OK: y=123456 (bytes=[]byte{0x1, 0xe2, 0x40})
    

    Note that the byte array value of big numbers is a compact machine representation and should not be mistaken for the string value, which can be retrieved by the usual String() method (or Text(int) for different bases) and set from a string value by the SetString(...) method:

    a := new(big.Int).SetInt64(42)
    a.String() // => "42"
    
    b, _ := new(big.Int).SetString("cafebabe", 16)
    b.String() // => "3405691582"
    b.Text(16) // => "cafebabe"
    b.Bytes()  // => []byte{0xca, 0xfe, 0xba, 0xbe}
    
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错