9

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
6
  • 3
    Int.Bytes() method?
    – icza
    May 25, 2018 at 12:42
  • so im using this now phrase := sum.Bytes() which does seem to convert the number to bytes, but im having issues reversing the process to get the original number back.. the original numbers type on return is not important, any idea how i can retrieve it
    – Kravitz
    May 25, 2018 at 12:54
  • 3
    Int.SetBytes() method. You really should start reading the docs.
    – icza
    May 25, 2018 at 12:55
  • 1
    Tried to read them thats why im here. still no luck with that but thanks anyway
    – Kravitz
    May 25, 2018 at 13:06
  • 1
    @Kravitz: then please show what you've tried using the correct methods as shown in the documentation. Bytes and SetBytes do what you've described.
    – JimB
    May 25, 2018 at 13:10

1 Answer 1

12

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}
1
  • 2
    Note that this byte encoding does not include the sign, it only stores/sets the absolute value. Feb 11, 2022 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.