rullzing
rullzing

Reputation: 642

string to big Int in Go?

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?

Upvotes: 20

Views: 30142

Answers (2)

peterSO
peterSO

Reputation: 166606

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

Upvotes: 46

gammazero
gammazero

Reputation: 953

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

Upvotes: 3

Related Questions