Jzala
Jzala

Reputation: 43

Generate crypto Random Integer beetwen min, max values

I trying to generate a random number beetwen a min value and a max value, but seems I'm lost with this, what is wrong?

package main

import (
    "crypto/rand"
    "encoding/binary"
    "fmt"
)

func genRandNum(min, max int8) int {
    var num int8
    binary.Read(rand.Reader, binary.LittleEndian, &num)
    return int(num*(max-min)+min)
}

func main() {
    // trying to get a random number beetwen -10 and 10
    fmt.Println(genRandNum(-10,10))
}

Upvotes: 3

Views: 3680

Answers (1)

jmaloney
jmaloney

Reputation: 12300

How about this

func main() {
    fmt.Println(genRandNum(-10, 10))
}

func genRandNum(min, max int64) int64 {
    // calculate the max we will be using
    bg := big.NewInt(max - min)

    // get big.Int between 0 and bg
    // in this case 0 to 20
    n, err := rand.Int(rand.Reader, bg)
    if err != nil {
        panic(err)
    }

    // add n to min to support the passed in range
    return n.Int64() + min
}

Go play

Upvotes: 6

Related Questions