转到Go中的Int字符串? [英] string to big Int in Go?

查看:47
本文介绍了转到Go中的Int字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,有没有一种方法可以将字符串(本质上是一个很大的数字)从字符串转换为Big int?

Is there a way to convert a string (which is essentially a huge number) from string to Big int in Go?

我试图先将其转换为字节数组

I tried to first convert it into bytes array

array:= [] byte(string)

然后将数组转换为BigInt.

Then converting the array into BigInt.

我认为可以,但是输出与原始输入不同.因此,我猜测转换由于某种原因未能正确执行.

I thought that worked, however, the output was different than the original input. So I'm guessing the conversion didn't do the right thing for some reason.

我要处理的数字超过300个数字,所以我认为我不能使用常规int.

The numbers I'm dealing with are more than 300 digits long, so I don't think I can use regular int.

关于什么是最佳方法的任何建议?

Any suggestions of what is the best approach for this?

推荐答案

大包装

导入数学/大"

func(* Int)SetString

func(z * Int)SetString(s字符串,基本int)(* Int,bool)

SetString将z设置为s的值(以给定的基数解释),并且返回z和一个指示成功的布尔值.整个字符串(不是只是一个前缀)必须对成功有效.如果SetString失败,则z的值未定义,但返回的值为nil.

SetString sets z to the value of s, interpreted in the given base, and returns z and a boolean indicating success. The entire string (not just a prefix) must be valid for success. If SetString fails, the value of z is undefined but the returned value is nil.

基本参数必须为0或2到MaxBase之间的值.如果base为0,字符串前缀确定实际的转换基准.一种前缀"0x"或"0X"选择基数为16;"0"前缀选择基数8,并使用"0b"或"0B"前缀选择基数2.否则,选择的基数是10.

The base argument must be 0 or a value between 2 and MaxBase. If the base is 0, the string prefix determines the actual conversion base. A prefix of "0x" or "0X" selects base 16; the "0" prefix selects base 8, and a "0b" or "0B" prefix selects base 2. Otherwise the selected base is 10.

例如,

package main

import (
    "fmt"
    "math/big"
)

func main() {
    n := new(big.Int)
    n, ok := n.SetString("314159265358979323846264338327950288419716939937510582097494459", 10)
    if !ok {
        fmt.Println("SetString: error")
        return
    }
    fmt.Println(n)
}

游乐场: https://play.golang.org/p/ZaSOQoqZB_

输出:

314159265358979323846264338327950288419716939937510582097494459

这篇关于转到Go中的Int字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆