dongshai8330 2017-06-11 10:24
浏览 314
已采纳

来自crypto / rand的随机64位整数

I want to generate 64-bit random integer using the secure crypto/rand package. I found this online:

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
}

But it seems to generate random bytes instead. I want a random 64-bit int. Namely, I want something like var i uint64 = rand(). Any ideas how to achieve this?

  • 写回答

2条回答 默认 最新

  • dousi6303 2017-06-11 10:28
    关注

    You can generate a random number with crypto.Rand, and then convert those bytes to an int64 using the binary package:

    func randint64() (int64, error) {
        var b [8]byte
        if _, err := rand.Read(b[:]); err != nil {
            return 0, err
        }
        return int64(binary.LittleEndian.Uint64(b[:])), nil
    }
    

    https://play.golang.org/p/2Q8tvttqbJ (result is cached)

    If you look at the source code for LittleEndian.Uint64, you can see it's simply performing a few bit operations on the data; something that you could implemented for yourself.

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

报告相同问题?