string to big Int in Go?

喜欢而已 提交于 2020-12-01 06:15:29

问题


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)

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.

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?


回答1:


Package big

import "math/big"

func (*Int) SetString

func (z *Int) SetString(s string, base int) (*Int, bool)

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.

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.

For example,

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

Playground: https://play.golang.org/p/ZaSOQoqZB_

Output:

314159265358979323846264338327950288419716939937510582097494459



回答2:


See Example for string to big int conversion.

package main


import (
    "fmt"
    "log"
    "math/big"
)

func main() {
    i := new(big.Int)
    _, err := fmt.Sscan("18446744073709551617", i)
    if err != nil {
        log.Println("error scanning value:", err)
    } else {
        fmt.Println(i)
    }
}

Output:

18446744073709551617


来源:https://stackoverflow.com/questions/46783352/string-to-big-int-in-go

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