在Go中使用大整数值?(ParseInt只能转换到“2147483647”吗?)

huangapple go评论93阅读模式
英文:

Using big integer values in Go? (ParseInt only converts up to "2147483647"?)

问题

如何在Go中将一个长字符串(50位数字)转换为整数?

我得到了以下代码的输出:

number = 2147483647

err = strconv.ParseInt: parsing "37107287533902102798797998220837590246510135740250": value out of range

似乎只能将数字转换为最大为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)
    }   
}
英文:

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

答案1

得分: 33

你需要使用math/big包,该包提供了任意精度的整数支持。

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("无法解释行 %#v\n", line)
        }
    }
}

这里有一个快速示例,展示了它的工作原理。

英文:

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.

huangapple
  • 本文由 发表于 2012年5月25日 09:32:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/10747411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定