Skip to content

Instantly share code, notes, and snippets.

@joelclermont
Created January 29, 2013 17:35
Show Gist options
  • Save joelclermont/4666034 to your computer and use it in GitHub Desktop.
Save joelclermont/4666034 to your computer and use it in GitHub Desktop.
Putting random numbers in your random numbers and doing random byte math is really random, right? Wrong.
' Because we cannot use the default randomizer, which is based on the
' current time (it will produce the same "random" number within a
' second), we will use a random number generator to seed the
' randomizer.
' Use a 4-byte array to fill it with random bytes and convert it then
' to an integer value.
Dim randomBytes As Byte() = New Byte(3) {}
' Generate 4 random bytes.
Dim rng As New RNGCryptoServiceProvider()
rng.GetBytes(randomBytes)
' Convert 4 bytes into a 32-bit integer value.
Dim seed As Integer = (randomBytes(0) And &H7F) << 24 Or randomBytes(1) << 16 Or randomBytes(2) << 8 Or randomBytes(3)
' Now, this is real randomization.
Dim random As New Random(seed)
@joelclermont
Copy link
Author

The comments make it that much more frustrating for me.

@joelclermont
Copy link
Author

By the way, they were afraid of collisions within a second, but instead generated an infinite recursion in the function that calls this nonsense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment