![](/img/trans.png)
[英]How to convert The int array to byte array? so that I can make a bitmap by byte array instead of byte array
[英]How can I convert a *big.Int into a byte array in golang
我試圖對一個大的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)
檢索它,並從字符串中進行設置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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.