douben6670 2016-09-28 19:31
浏览 533
已采纳

如何在Go中生成随机uint64?

Go's math/random library is missing a function to generate 64-bit numbers. This has been an open issue for about four years. In the meantime, what does a workaround look like?

  • 写回答

3条回答 默认 最新

  • douhuan1905 2016-09-28 19:41
    关注

    The easiest would be to call rand.Uint32() twice:

    func Uint64() uint64 {
        return uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
    }
    

    Another option is to call rand.Read() (was added in Go 1.7) to read 8 bytes, then use the encoding/binary package to obtain a uint64 value from it:

    func Uint64() uint64 {
        buf := make([]byte, 8)
        rand.Read(buf) // Always succeeds, no need to check error
        return binary.LittleEndian.Uint64(buf)
    }
    

    Note: as the doc of rand.Read() states, it always reads as many bytes as the length of the passed slice, and it always returns nil error, so no need to check error in this case.

    Note #2: you could also use binary.BigEndian instead of binary.LittleEndian, as we're generating a random number using all its bytes, order of bytes is completely irrelevant.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图