Question

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

Was it helpful?

Solution

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");
}

OTHER TIPS

    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

Here's one that would return a 256-bit hex string (8x8=256):

private static string RandomHexString()
{
    // 64 character precision or 256-bits
    Random rdm = new Random();
    string hexValue = string.Empty;
    int num;

    for (int i = 0; i < 8; i++)
    {
        num = rdm.Next(0, int.MaxValue);
        hexValue += num.ToString("X8");
    }

    return hexValue;
}

.... with LINQ

private static readonly Random _RND = new Random();

public static string GenerateHexString(int digits) {
    return string.Concat(Enumerable.Range(0, digits).Select(_ => _RND.Next(16).ToString("X")));
}

If you want it to be a cryptographically secure you should use RNGCryptoServiceProvider.

public static string BuildSecureHexString(int hexCharacters)
{
    var byteArray = new byte[(int)Math.Ceiling(hexCharacters / 2.0)];
    using (var rng = new RNGCryptoServiceProvider())
    {
        rng.GetBytes(byteArray);
    }
    return String.Concat(Array.ConvertAll(byteArray, x => x.ToString("X2")));
}

Create an n character (~n/2 byte), random string of hex:

var randBytes = new byte[n/2 + n%2>0?1:0];
new Random().NextBytes(randBytes);
var hex = BitConverter.ToString(randBytes).Replace("-", string.Empty).Substring(0,n);

Have you considered Base64 strings? Depending on your application, they can often more useful. They're guaranteed to be ASCII and provide ~4/3 characters per input byte. To create an n character string:

var randBytes = new byte[(n/4 + n%4>0?1:0)*3];
new Random().NextBytes(randBytes);
var base64 = Convert.ToBase64String(randBytes).Substring(0,n);

Obviously, you can omit the .Substring(0,n) if your application does not require either an odd number of hex characters or a Base64 that is not a multiple of 4 characters.

Feel free to extend the examples by making Random() static, as other posters have suggested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top