【问题标题】:How can I convert a *big.Int into a byte array in golang如何将 *big.Int 转换为 golang 中的字节数组
【发布时间】:2018-05-25 12:41:17
【问题描述】:

我试图对一个大的 int 数进行计算,然后将结果转换为字节数组,但我不知道该怎么做,这就是我目前所处的位置。大家有什么想法

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

【问题讨论】:

  • Int.Bytes() 方法?
  • 所以我现在使用这个phrase := sum.Bytes() 似乎确实将数字转换为字节,但我在反转过程以获取原始数字时遇到问题.. 返回时的原始数字类型并不重要,知道我如何检索它
  • Int.SetBytes() 方法。你真的应该开始阅读文档了。
  • 试图阅读它们,这就是我在这里的原因。仍然没有运气,但无论如何谢谢
  • @Kravitz:那么请展示您使用文档中所示的正确方法尝试过的内容。 BytesSetBytes 按照你的描述做。

标签: arrays go go-ethereum geth


【解决方案1】:

尝试使用Int.Bytes() 获取字节数组表示,并尝试使用Int.SetBytes([]byte) 从字节数组中设置值。例如:

x := new(big.Int).SetInt64(123456)
fmt.Printf("OK: x=%s (bytes=%#v)\n", 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)\n", y, y.Bytes())
// OK: y=123456 (bytes=[]byte{0x1, 0xe2, 0x40})

请注意,大数的字节数组值是一种紧凑的机器表示,不应误认为是字符串值,可以通过通常的String() 方法(或Text(int) 用于不同的基数)检索并设置从SetString(...) 方法的字符串值:

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}

【讨论】:

  • 注意这个字节编码不包含符号,它只存储/设置绝对值。
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2022-10-07
  • 2018-12-09
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
相关资源
最近更新 更多