我试图对一个大的 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()
获取字节数组表示,并使用 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)
获取不同的bases) 并通过 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}
关于arrays - 如何将 *big.Int 转换为 golang 中的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50529494/