Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly generated hexadecimal number in C#

Tags:

c#

random

hex

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

like image 703
shizbiz Avatar asked Jun 28 '09 02:06

shizbiz


People also ask

Can you generate random numbers in C?

In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX].


2 Answers

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"); } 
like image 55
mmx Avatar answered Sep 29 '22 06:09

mmx


    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.

like image 43
womp Avatar answered Sep 29 '22 06:09

womp