Alex Rivera | Logout

Randomly generated hexadecimal number in C#

Asked 2009-06-28T02:29:04.543
41

How can I generate a random hexadecimal number with a length of my choice using C#?

Edit
Report

1 Answer

63
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");
}
answered 2009-06-28T02:37:26.880

Your Answer