Randomly generated hexadecimal number in C#
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.
Depends on how random you want it, but here are 3 alternatives: 1) I usually just use Guid.NewGuid and pick a portion of it (dep. on how large number I want).
2) System.Random (see other replies) is good if you just want 'random enough'.
3) System.Security.Cryptography.RNGCryptoServiceProvider