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}
Int.Bytes()
method?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 itInt.SetBytes()
method. You really should start reading the docs.Bytes
andSetBytes
do what you've described.