Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a *big.Int into a byte array in 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
like image 911
Kravitz Avatar asked May 25 '18 12:05

Kravitz


People also ask

How do I convert an integer to a byte array?

The Ints class also has a toByteArray() method that can be used to convert an int value to a byte array: byte[] bytes = Ints. toByteArray(value);

How do I create a byte array in Golang?

To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer. The byte type represents ASCII characters, while the rune data type represents a broader set of Unicode characters encoded in UTF-8 format.

What is [] byte Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).


1 Answers

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)\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})

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}
like image 137
maerics Avatar answered Sep 26 '22 01:09

maerics