You want to create a statistically random number quickly.
Create an instance of the System.Random class, and call the Next or NextDouble method.
class uses a pseudorandom number generator, which means that it uses an algorithm to generate
To use the Random class, you simply create an instance and call either Next or NextDouble . NextDouble returns a double-precision floating-point number greater than or equal to 0.0, and less than 1.0. Next generates an integer within the maximum and minimum range you specify.
Dim RandomGenerator As New Random() ' Retrieve a random fraction number from 0.0 to 1.0. Dim RandomDouble As Double = RandomGenerator.NextDouble() ' Retrieve a random integer number from 1 to 6. Dim RandomInt As Integer = RandomGenerator.Next(1, 7) ' Retrieve another random integer from 1 to 6. RandomInt = RandomGenerator.Next(1, 7)
Notice that the maximum bound for the Next method is always one higher than the maximum integer in your range.
class is ideal when you need to generate a quick random value for a game, simulation, or test. However, it's not suitable for use with cryptography, because an attacker can guess the "random" number you will generate by examining previous random values and determining how you are seeding the random generator. If you need
By default, the
' Because this loop executes so quickly, it's easy to create two ' Random objects with the same seed and end up with ' short sequences of identical numbers (like 8888333322). Dim i As Integer For i = 0 To 10 Dim RandomGenerator As New Random() Console.WriteLine(RandomGenerator.Next(1, 7)) Next
You want to convert a base 10 number to a hexadecimal, octal, or binary number (or vice versa).
Use the overloaded
Although you can't work directly with non–base 10
Dim Number As Integer = 3023 Console.WriteLine("Binary: " & Convert.ToString(Number, 2)) Console.WriteLine("Octal: " & Convert.ToString(Number, 8)) Console.WriteLine("Hexadecimal: " & Convert.ToString(Number, 16))
The output for this code is:
Binary: 101111001111 Octal: 5717 Hexadecimal: bcf
You can also use the shared Convert.ToInt32 , Convert.ToInt16 , or Convert.ToInt64 methods to convert a non–base 10 number from a string into an integer type:
Dim Binary As String = "01" Dim Number As Integer = Convert.ToInt32(Binary, 2) ' Double the number. Number *= 2 ' Convert it back to binary. Binary = Convert.ToString(Number, 2) ' Binary is now "10".
If you need to perform calculations with non–base 10 numbers, you have two choices. You could use the ToInt32 number to convert your numbers to decimal, perform the calculation, and then use ToString to convert the number back into its native representation, as shown above. Alternatively, you could create a custom class that represents the number and provides dedicated methods such as Add , Subtract , Multiply , and so on, which perform native calculations. Recipes 2.5 and 2.6 show similar techniques with classes that represent complex numbers and vectors.