【问题标题】:Golang overflows int64Golang 溢出 int64
【发布时间】:2015-06-14 19:00:06
【问题描述】:

我尝试使用此代码,但给我一个错误:常量 100000000000000000000000 overflows int64

我该如何解决这个问题?

// Initialise big numbers with small numbers
count, one := big.NewInt(100000000000000000000000), big.NewInt(1)

【问题讨论】:

    标签: go biginteger int64


    【解决方案1】:

    例如:

    count,one := new(big.Int), big.NewInt(1)
    count.SetString("100000000000000000000000",10)
    

    链接: http://play.golang.org/p/eEXooVOs9Z

    【讨论】:

      【解决方案2】:

      它不起作用,因为在后台,big.NewInt 实际上分配了一个 int64。您要分配给 big.NewInt 的数字需要超过 64 位才能存在,因此它失败了。

      但是,如果你想在 MaxInt64 下添加两个大数,你可以这样做!即使总和大于 MaxInt64。这是我刚刚写的一个例子(http://play.golang.org/p/Jv52bMLP_B):

      func main() {
          count := big.NewInt(0);
      
          count.Add( count, big.NewInt( 5000000000000000000 ) );
          count.Add( count, big.NewInt( 5000000000000000000 ) );
      
          //9223372036854775807 is the max value represented by int64: 2^63 - 1
          fmt.Printf( "count:     %v\nmax int64:  9223372036854775807\n", count );
      }
      

      结果:

      count:     10000000000000000000
      max int64:  9223372036854775807
      

      现在,如果您仍然对 NewInt 的底层工作原理感到好奇,这里是您正在使用的函数,取自 Go 的文档:

      // NewInt allocates and returns a new Int set to x.
      func NewInt(x int64) *Int {
          return new(Int).SetInt64(x)
      }
      

      来源:

      https://golang.org/pkg/math/big/#NewInt

      https://golang.org/src/math/big/int.go?s=1058:1083#L51

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-07
        • 1970-01-01
        • 1970-01-01
        • 2012-02-07
        • 1970-01-01
        • 1970-01-01
        • 2014-02-27
        • 2016-09-26
        相关资源
        最近更新 更多