How do you convert a long string of digits (50 digits) into an integer in Go?
I am getting the output for the code below:
number = 2147483647
err = strconv.ParseInt: parsing "37107287533902102798797998220837590246510135740250 ": value out of range
It seems to be able to convert numbers only up to 2147483647.
package main
import "fmt"
import "io/ioutil"
import "strings"
import "strconv"
var (
number int64
)
func main() {
fData,err := ioutil.ReadFile("one-hundred_50.txt")
if err != nil {
fmt.Println("Err is ",err)
}
strbuffer := string(fData)
lines := strings.Split(strbuffer, "\n")
for i, line := range lines {
fmt.Printf("%d: %s\n", i, line)
number, err := strconv.Atoi(line)
fmt.Println("number = ", number)
fmt.Println("err = ", err)
}
}
You want the math/big package, which provides arbitrary-precision integer support.
import "math/big"
func main() {
// ...
for i, line := range lines {
bi := big.NewInt(0)
if _, ok := bi.SetString(line, 10); ok {
fmt.Printf("number = %v\n", bi)
} else {
fmt.Printf("couldn't interpret line %#v\n", line)
}
}
}
Here's a quick example of it working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With