将一个bigint转换为字符串在Go中

huangapple go评论97阅读模式
英文:

Convert a bigint to a string in Go

问题

如何将一个大整数转换为字符串(或整数)在Golang中?

bigint := big.NewInt(123) //这是我有的
bigstr = "123" //这是我想要的
英文:

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

得分: 36

只需使用String方法:http://golang.org/pkg/math/big/#Int.String

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

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

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

答案2

得分: 4

你问如何将bigInt转换为字符串或整数,被接受的答案只解释了如何转换为字符串。

所以你有你的bigint := big.NewInt(123)


你可以用两种方式将bigInt转换为整数:

  • 使用.Int64()。使用yourInt := bigint.Int64()
  • 使用.Uint64()。使用yourUint := bigint.Uint64()

之所以有两种方法是因为uint可以容纳两倍大的数字,有时你知道答案是正数。请注意,如果数字大于int64/uint64的最大可能值:

> 如果x无法表示为int64,则结果是未定义的。


为了完整起见,要转换为字符串,只需使用.String() bigstr := bigint.String()

英文:

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

答案3

得分: 0

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

英文:

I used the following:

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

huangapple
  • 本文由 发表于 2012年8月5日 02:13:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/11810948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定