Convert a bigint to a string in Go

泄露秘密 提交于 2019-12-04 18:14: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:


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

bigint := big.NewInt(123)
bigstr := bigint.String()



回答2:


I used the following:

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



回答3:


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()



来源:https://stackoverflow.com/questions/11810948/convert-a-bigint-to-a-string-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!