Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go print large number

I am currently doing the Go Lang tutorial, "Numeric Constants" to be precise. The example code starts with the following statement:

const (
    // Create a huge number by shifting a 1 bit left 100 places.
    // In other words, the binary number that is 1 followed by 100 zeroes.
    Big = 1 << 100
    // Shift it right again 99 places, so we end up with 1<<1, or 2.
    Small = Big >> 99
)

The constant Big is obviously huge, and I am trying to print it and its type, like this:

fmt.Printf("%T", Big)
fmt.Println(Big)

However, I get the following error for both lines:

# command-line-arguments ./compile26.go:19: constant 1267650600228229401496703205376 overflows int

I would try casting Big to some other type, such as uint64, which it overflowed with the same error, or just convert it to a string, but when trying Big.String() I get the following error:

Big.String undefined (type int has no field or method String)

It appears that its type is int, yet I can't print it or cast it to anything and it overflows all methods. What do I do with this number/object and how do I print it?

like image 504
arik Avatar asked Oct 10 '16 21:10

arik


People also ask

What is %+ V in Golang?

General: %v the value in a default format when printing structs, the plus flag (%+v) adds field names %#v a Go-syntax representation of the value %T a Go-syntax representation of the type of the value %% a literal percent sign; consumes no value.

What is big int Golang?

Golang doesn't check for overflows implicitly and so this may lead to unexpected results when a number larger than 64 bits are stored in a int64. To solve this problem, Go provides the Package “big” which implements arbitrary-precision arithmetic (big numbers).


1 Answers

That value is larger than any 64 bit numeric type can hold, so you have no way of manipulating it directly.

If you need to write a numeric constant that can only be manipulated with the math/big package, you need to store it serialized in a format that package can consume. Easiest way is probably to use a base 10 string:

https://play.golang.org/p/Mzwox3I2SL

bigNum := "1267650600228229401496703205376"
b, ok := big.NewInt(0).SetString(bigNum, 10)
fmt.Println(ok, b)
// true 1267650600228229401496703205376
like image 110
JimB Avatar answered Sep 29 '22 20:09

JimB