Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
rullzing Avatar asked Oct 17 '17 05:10

rullzing


People also ask

How do you cast to int in go?

In order to convert string to integer type in Golang, you can use the following methods. You can use the strconv package's Atoi() function to convert the string into an integer value. Atoi stands for ASCII to integer. The Atoi() function returns two values: the result of the conversion, and the error (if any).

What is big int Golang?

Golang doesn't check for overflows implicitly and so this may lead to unexpected results when a number larger than 64 bits are stored in a int64. To solve this problem, Go provides the Package “big” which implements arbitrary-precision arithmetic (big numbers).

How big is a big INT Golang?

There is no explicit limit. The limit will be your memory or, theoretically, the max array size (2^31 or 2^63, depending on your platform).

How do you convert type in GO?

How do you convert types of Go? The strconv. Itoa method from the strconv package in the Go standard library can be used to convert numbers to strings. If you enter a number or a variable into the method's parenthesis, the numeric value is converted to a string value.


1 Answers

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
like image 94
peterSO Avatar answered Oct 19 '22 05:10

peterSO