You may use big.NewInt()
to create a new big.Int
value initialized with an int64
value. It returns you a pointer (*big.Int
). Alternatively you could simply use the builtin new()
function to allocate a big.Int
value which will be 0
like this: new(big.Int)
, or since big.Int
is a struct type, a simple composite literal would also do: &big.Int{}
.
Once you have a value, you may use Int.SetString()
to parse and set a number given as string
. You can pass the base of the string number, and it also returns you a bool
value indicating if parsing succeeded.
Then you may use Int.Add()
and Int.Sub()
to calculate the sum and difference of 2 big.Int
numbers. Note that Add()
and Sub()
write the result into the receiver whose method you call, so if you need the numbers (operands) unchanged, use another big.Int
value to calculate and store the result.
See this example:
numA := "340282366920938463463374607431768211456"
numB := "17014118346046923173168730371588410572"
ba, bb := big.NewInt(0), big.NewInt(0)
if _, ok := ba.SetString(numA, 10); !ok {
panic("invalid numA")
}
if _, ok := bb.SetString(numB, 10); !ok {
panic("invalid numB")
}
sum := big.NewInt(0).Add(ba, bb)
fmt.Println("a + b =", sum)
diff := big.NewInt(0).Sub(ba, bb)
fmt.Println("a - b =", diff)
Output (try it on the Go Playground):
a + b = 357296485266985386636543337803356622028
a - b = 323268248574891540290205877060179800884