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: https://play.golang.org/p/HxAb6Rs_Uj
Any help is appreciated. Thank you.
If I understand correctly, the issue you're having is that the random number appears to always have the same number of digits as the maximum allowed value, right? When I run the code, this is not the case. Here's an output I just observed:
3859736307910539847452366166956263595094585475969163479420172104717272049811
65719900872761032562423535702578352960653752260368991759410130265294153783
In the playground, I believe the random seed and clock time are fixed, so you'll see the same result repeatedly. But running locally, I see the expected variation in the length of the output.
UPDATE
You may wonder why you can run this code a bunch of times and observe that the length of the random number is very often close to the length of the maximum value.
A little math explains this. Let's imagine we're picking a number between 0 and 999. How many numbers in that range have:
Similarly, with your very large maximum value, most of the numbers that can be picked will be very close to that maximum length. It will be rare to see a number two digits short of that length. (You should see them on the order of 1% of the time.)