如何在golang中将uint64转换为big.Int?

Hos*_*ein 0 biginteger type-conversion go

我想知道如何将其转换uint64big.Intgolang?最短的路.

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

我不喜欢它导致它很长,嵌套转换太多,如果它存在,我宁愿使用内置函数.

icz*_*cza 7

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

var x uint64 = 10

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

fmt.Println(i) // Prints 10
Run Code Online (Sandbox Code Playgroud)

Go Playground尝试一下.

手动转换uint64int64(如您的示例中)时应小心,因为可能会发生溢出而您不会收到通知,但最终会出现负值.

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

i := big.NewInt(int64(x))
Run Code Online (Sandbox Code Playgroud)

Go Playground尝试这个.