21

How do one convert a big int to a string (or integer) in Golang?

bigint := big.NewInt(123) //This is what I have
bigstr = "123" //This is what I want
1
  • 2
    Thanks for the comment pst. After hours of searching, I would say that the documentation is not great on bigints. For instance, I still couldn't figure out for the life of me how to convert from a string to a bigint. Commented Aug 4, 2012 at 23:20

3 Answers 3

41

Just use the String method : http://golang.org/pkg/math/big/#Int.String

bigint := big.NewInt(123)
bigstr := bigint.String()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, cyberdelia. Should I make a new question, or can I ask you how to convert the other way around: from a string to a bigint? (Again, I couldn't find the answer anywhere).
@BurntSushi5 - Thank you so much! That is a great little string to big.Int example: bigint.SetString("123", 10)
7

You asked how to convert a bigInt to string or to int, the accepted answer explains only how to convert to string.

So you have your bigint := big.NewInt(123)


You can convert your bigInt to integer in two possible ways:

  • using .Int64(). With yourInt := bigint.Int64()
  • using .Uint64(). With yourUint := bigint.Uint64()

The reason for two methods is that uint holds 2 time bigger numbers, and sometimes you know that the answer is positive. Beware that if the number is bigger than the maximum possible for int64/uint64:

If x cannot be represented in an int64, the result is undefined.


And for completeness, to convert to string, just use .String() bigstr := bigint.String()

Comments

0

I used the following:

bigint := big.NewInt(1231231231231)
bigstr := fmt.Sprint(bigint)

2 Comments

Calling bigint.String() directly (instead of via interface{} of fmt) is simpler and more efficient. The only reason to use the fmt package for this is if you wanted to make use of special formatting.
I used the bigint.String() in a really big int and obtained something like 1.2123423534546e308

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.