How can I generate a random hexadecimal number with a length of my choice using C#?
+8
A:
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");
}
Mehrdad Afshari
2009-06-28 02:37:26
+3
A:
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.
womp
2009-06-28 02:37:47
It'll work only if `length <= 8` as `int.MaxValue` fits in 8 hex digits.
Mehrdad Afshari
2009-06-28 03:00:02
If he really does want the hex string to be of a length of his choice, you will need code that calculates the minimum number with hex length 'x' and maximum with length 'x'.
colithium
2009-06-28 03:00:17
Yep. I left that out on purpose, but you would basically just have to do a conversion on 0xF? ('scuse my regular expression) to find whatever integer matched your desired length.
womp
2009-06-28 04:03:19
+2
A:
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
KristoferA - Huagati.com
2009-06-28 02:43:01
Slicing up a GUID seems like a real bad idea to me. They're only unique taken as a whole. Many bits of a GUID certainly don't qualify as random.
spender
2009-06-28 02:49:51
@spender is correct, for instance many GUIDs contain the MAC address of the PC generating them.
Eric Haskins
2009-06-28 04:48:37
Eh, no, the mac-address based guids were retired back in 2000-ish as they were considered a potential security issue. GUIDs are now generated by a random number generator (122 bits random, 6 bits non-random). Either way, using a 32 (or more) bit slice of a guid gives a more random number than System.Random.That is - unless you call UuidCreateSequential which was added for backwards compatibility in case anyone want old style guids, but that is a different story.
KristoferA - Huagati.com
2009-06-28 08:41:33
Yes. See the documentation for System.Random at http://msdn.microsoft.com/en-us/library/system.random.aspx
KristoferA - Huagati.com
2009-06-28 12:39:06