mardi 27 juin 2017

How to generate a variable length random number in Go

I'm trying to generate a random integer with variable length in Go but I always get the number filling the total length. Here's my code:

package main

import (
    "fmt"
    "math/big"
    "crypto/rand"
)

const ResultsPerPage = 30

var (
        total = new(big.Int).SetBytes([]byte{
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
                0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
        })
        pages = new(big.Int).Div(total, big.NewInt(ResultsPerPage))
        random *big.Int
        err error
)

func main() {

fmt.Println(pages)
fmt.Println(randomString(pages))
}

func randomString(l *big.Int) string {
  random, err = rand.Int(rand.Reader, l)
  fmtrandom := fmt.Sprint(random)
  return string(fmtrandom)
}

Outputs

3859736307910539847452366166956263595094585475969163479420172104717272049811
3479662380009045046388212253547512051795238437604387552617121977169155584415

Code sample: http://ift.tt/2tfuB3p

Any help is appreciated. Thank you.




Aucun commentaire:

Enregistrer un commentaire