donglong9745 2017-02-09 18:25
浏览 59
已采纳

移位整数时如何绕过Go int64值限制?

I'm trying with Go to get values of KiB, MiB, ..., ZiB, Yib which are respectively KibiByte, MebiByte, ..., ZebiByte, YobiByte.

My code in Golang is:

package main 
import ( 
    "fmt"
)

func main() {
    s := []string{"KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}

    for k,v := range(s) {
        fmt.Printf("%s: %v
", v, 1 << uint64(10 * (k+1)))
    }
}

But, the values of ZiB and YiB overflows Go uint64 and this why I'm having this output:

KiB: 1024
MiB: 1048576
GiB: 1073741824
TiB: 1099511627776         // exceeds 1 << 32
PiB: 1125899906842624
EiB: 1152921504606846976
ZiB: 0                    // exceeds 1 << 64
YiB: 0                    // exceeds 1 << 64

Otherwise, with the same shifting logic in Python3 within this code:

a = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
for k,v in enumerate(a):
    print("{}: {}".format(v, 1 << (10 *(k+1))))

The output is correct, like the output below:

KiB: 1024
MiB: 1048576
GiB: 1073741824
TiB: 1099511627776
PiB: 1125899906842624
EiB: 1152921504606846976
ZiB: 1180591620717411303424
YiB: 1208925819614629174706176

So, how can I bypass Go uint64 limits and get the correct values using shifting integers like what I can get from shifting integers using Python.

Thanks.

  • 写回答

1条回答 默认 最新

  • dqwh1201 2017-02-09 18:33
    关注

    You can't work with numbers that require more than 64bits with a primitive uint64. Python has arbitrary precision integers, and to get the same in Go you need to use the math/big package.

    s := []string{"KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
    
    one := big.NewInt(1)
    for k, v := range s {
        fmt.Printf("%s: %v
    ", v, new(big.Int).Lsh(one, uint(10*(k+1))))
    }
    

    https://play.golang.org/p/i5v5P5QgQb

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大