I have a byte array, with a fixed length of 4.
token := make([]byte, 4)
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?
Previous solutions get a random number to designate a random letter by calling rand. Intn() which delegates to Rand. Intn() which delegates to Rand. Int31n() .
Go rand. The rand. Intn function returns, as an int, a non-negative pseudo-random number in [0,n) from the default source. The example prints five random integers. To get different pseudo random values, we seed the random generator with time.
Next up, we need to randomly choose a character from the string, we can do that by importing the rand package in Golang. The rand function has a function called Intn, which generates a random number between 0 (inclusive) to the provided number(non-inclusive).
A hash is a mathematical function that converts an input of arbitrary length into an encrypted output of a fixed length.
Package rand
import "math/rand"
func Read
func Read(p []byte) (n int, err error)
Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error.
func (*Rand) Read
func (r *Rand) Read(p []byte) (n int, err error)
Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error.
For example,
package main import ( "math/rand" "fmt" ) func main() { token := make([]byte, 4) rand.Read(token) fmt.Println(token) }
Output:
[187 163 35 30]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With