duanchu9914
2012-05-25 01:32
浏览 102
已采纳

在Go中使用大整数值? (ParseInt仅转换为“ 2147483647”吗?)

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, "
")

    for i, line := range lines {
        fmt.Printf("%d: %s
", i, line)
        number, err := strconv.Atoi(line)
        fmt.Println("number = ", number)
        fmt.Println("err = ", err)
    }   
}

图片转代码服务由CSDN问答提供 功能建议

如何在Go语言中将一长串数字(50位数字)转换为整数? \ n

我正在获取以下代码的输出:

  number = 2147483647 
   
 
 

err = strconv.ParseInt:解析“ 37107287533902102798797998220837590246510135740250 ”:值超出范围

它似乎只能将数字转换为 2147483647。

 程序包主
 
导入“ fmt” 
导入“ io / ioutil” 
导入“字符串” 
导入“ strconv” 
 
var(
号 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,“ 
”)
 
 for i,line:=范围线{
 fmt.Printf(“  %d:%s 
“,i,行)
数字,错误:= strconv.Atoi(line)
 fmt.Println(” number =“,number)
 fmt.Println(”  err =“,err)
} 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougudu3564 2012-05-25 01:41
    已采纳

    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
    ", bi)
            } else {
                fmt.Printf("couldn't interpret line %#v
    ", line)
            }
        }
    }
    

    Here's a quick example of it working.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题