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

来自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?

图片转代码服务由CSDN问答提供 功能建议

我想使用安全的 crypto / rand 包生成64位随机整数。 我在网上找到了这个文件:

 包main 
 
import(
“ crypto / rand” 
“ encoding / base64” 
)
 
 // GenerateRandomBytes 返回安全生成的随机字节。
 //如果系统的安全随机数生成器无法正确运行,则将返回错误,在这种情况下,调用者不应继续。
func GenerateRandomBytes(n int  )([[byte,error){
b:= make([] byte,n)
 _,err:= rand.Read(b)
 //注意err == nil仅当我们读取len(  b)个字节。
 if err!= nil {
返回nil,err 
} 
 
返回b,nil 
} 
   
 
 

它似乎会生成随机字节。 我想要一个随机的64位int。 即,我想要类似 var i uint64 = rand()的东西。 任何想法如何实现这一目标?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    打赏 评论
  • dqp4933 2019-05-05 02:17

    You also use rand.Int in crypto/rand package

    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
    }
    

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

    打赏 评论

相关推荐 更多相似问题