Golang overflows int64

7.6k views Asked by At

I try to use this code, but gives me an error: constant 100000000000000000000000 overflows int64

How can I fix that ?

// Initialise big numbers with small numbers
count, one := big.NewInt(100000000000000000000000), big.NewInt(1)
2

There are 2 answers

0
AudioBubble On BEST ANSWER

for example so:

count,one := new(big.Int), big.NewInt(1)
count.SetString("100000000000000000000000",10)

link: http://play.golang.org/p/eEXooVOs9Z

0
Katamaritaco On

It won't work because under the hood, big.NewInt is actually allocating an int64. The number that you want to allocate into a big.NewInt would need more than 64bits to exist, so it failed.

However, with how big works, if you wanted to add two large numbers below MaxInt64, you can do that! Even if the sum is greater than MaxInt64. Here is an example I just wrote up (http://play.golang.org/p/Jv52bMLP_B):

func main() {
    count := big.NewInt(0);

    count.Add( count, big.NewInt( 5000000000000000000 ) );
    count.Add( count, big.NewInt( 5000000000000000000 ) );

    //9223372036854775807 is the max value represented by int64: 2^63 - 1
    fmt.Printf( "count:     %v\nmax int64:  9223372036854775807\n", count );
}

Which results in:

count:     10000000000000000000
max int64:  9223372036854775807

Now, if you're still curious about how NewInt works under the hood, here is the function you're using, taken from Go's documentation,:

// NewInt allocates and returns a new Int set to x.
func NewInt(x int64) *Int {
    return new(Int).SetInt64(x)
}

Sources:

https://golang.org/pkg/math/big/#NewInt

https://golang.org/src/math/big/int.go?s=1058:1083#L51