Go 从加密/rand随机64位整数

Go 从加密/rand随机64位整数,go,random,Go,Random,我想使用securecrypto/rand包生成64位随机整数。我在网上找到这个: package main import ( "crypto/rand" "encoding/base64" ) // GenerateRandomBytes returns securely generated random bytes. // It will return an error if the system's secure random // number generator f

我想使用secure
crypto/rand
包生成64位随机整数。我在网上找到这个:

package main

import (
    "crypto/rand"
    "encoding/base64"
)

// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)
    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
        return nil, err
    }

    return b, nil
}

但它似乎会生成随机字节。我想要一个随机的64位整数。也就是说,我想要类似于
var I uint64=rand()。有没有办法做到这一点?

您可以使用生成一个随机数,然后使用软件包将这些字节转换为int64:

(结果被缓存)


如果您查看,您可以看到它只是对数据执行一些位操作;您可以自己实现的东西。

您还可以在
加密/rand
包中使用
rand.Int

func randint64() (int64, error) {
    val, err := rand.Int(rand.Reader, big.NewInt(int64(math.MaxInt64)))
    if err != nil {
        return 0, err
    }
    return val.Int64(), nil
}

您不知道如何将8个随机字节转换为随机64位整数?可能是重复的,而不是重复的,@icza。他想使用密码随机性。谢谢。不知道二进制编码包的名称。
func randint64() (int64, error) {
    val, err := rand.Int(rand.Reader, big.NewInt(int64(math.MaxInt64)))
    if err != nil {
        return 0, err
    }
    return val.Int64(), nil
}