在Go中生成一个随机的,固定长度的字节数组 [英] Generating a random, fixed-length byte array in Go

查看:276
本文介绍了在Go中生成一个随机的,固定长度的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,固定长度为4.

I have a byte array, with a fixed length of 4.

token := make([]byte, 4)

我需要将每个字节设置为随机字节.在最有效的情况下,我该怎么办?就我而言,math/rand方法不提供随机字节功能.

I need to set each byte to a random byte. How can I do so, in the most efficient matter? The math/rand methods do not provide a Random Byte function, as far as I am concerned.

也许有内置的方法,还是应该生成一个随机字符串并将其转换为字节数组?

Perhaps there is a built-in way, or should I go with generating a random string and converting it to a byte array?

推荐答案

包裹兰特

import "math/rand" 

功能阅读

func Read(p []byte) (n int, err error)

Read从默认Source生成len(p)个随机字节,然后写入 他们变成p.它总是返回len(p)和nil错误.

Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error.

f unc(* Rand)阅读

func (r *Rand) Read(p []byte) (n int, err error)

Read生成len(p)个随机字节并将其写入p中.总是这样 返回len(p)和nil错误.

Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error.

例如,

package main

import (
    "math/rand"
    "fmt"
)

func main() {
    token := make([]byte, 4)
    rand.Read(token)
    fmt.Println(token)
}

输出:

[187 163 35 30]

这篇关于在Go中生成一个随机的,固定长度的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆