2017-06-11 69 views
0

我想使用安全crypto/rand包生成64位随机整数。我发现这个在线: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()。任何想法如何实现这一目标?

+0

你不知道如何将8个随机字节转换为一个随机的64位整数? –

+0

[你如何在Go中产生一个随机的uint64?]可能的重复(https://stackoverflow.com/questions/39756133/how-do-you-generate-a-random-uint64-in-go/39756320#39756320 ) – icza

+0

不重复,@icza。他想要使用密码随机性。 –

回答

1

可以产生一个随机数与crypto.Rand,然后使用binary包的字节转换为Int64:

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(结果缓存)

如果你看一下source code for LittleEndian.Uint64,你可以看到它只是对数据执行一些操作;你可以为自己实施的东西。

+0

谢谢。不知道二进制编码包。 – typos