How can I generate a random hexadecimal number with a length of my choice using C#?
In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX].
static Random random = new Random(); public static string GetRandomHexNumber(int digits) { byte[] buffer = new byte[digits / 2]; random.NextBytes(buffer); string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray()); if (digits % 2 == 0) return result; return result + random.Next(16).ToString("X"); }
Random random = new Random(); int num = random.Next(); string hexString = num.ToString("X");
random.Next() takes arguments that let you specify a min and a max value, so that's how you would control the length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With