【问题标题】:How to convert a uint64 to big.Int in golang?如何将 uint64 转换为 golang 中的 big.Int?
【发布时间】:2023-03-31 08:10:02
【问题描述】:

我想知道如何在 golang 中将 uint64 转换为 big.Int?最短的方式。

我试过new(big.Int).SetInt64(int64(a uint64 number))

我不喜欢它,因为它很长,嵌套转换太多,如果存在的话,我宁愿使用内置函数。

【问题讨论】:

标签: go type-conversion biginteger


【解决方案1】:

最短且最安全的方法是使用Int.SetUint64() 方法:

var x uint64 = 10

i := new(big.Int).SetUint64(x)

fmt.Println(i) // Prints 10

Go Playground 上试用。

手动将uint64 转换为int64 时应小心(如您的示例所示),因为可能会发生溢出,您不会收到通知,但最终会得到一个负值。

如果您可以确定该值适合int64,则使用big.NewInt() 函数会更短:

i := big.NewInt(int64(x))

Go Playground 上试试这个。

【讨论】:

  • 谢谢!不知何故,我错过了 SetUint64 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
相关资源
最近更新 更多