Generate HEX number.

  • Thread starter Thread starter Zeya
  • Start date Start date
You can generate a regular integer number. If you want to represent it
in form of a hex string, just format it: Int32.ToString("X").
 
Thanks Thi for the quick response.

The catch is the HEX has to be 16 digit/character, how do I achieve
this?
 
Hi Zera, 16 digits -> 8 bytes. You can generate 8 bytes then
concatenate them.

To pad 0 to the left of each byte, you can use the easy-to-understand
String.PadLeft method and don't have to study the complexity of format
specifier used by String.Format.

Random theRandom = new Random();
byte[] theBytes = new byte[8];
theRandom.NextBytes(theBytes);
StringBuilder buffer = new StringBuilder(16);
for (int i = 0; i < 8; i++) {
buffer.Append(theBytes.ToString("X").PadLeft(2));
}

string myHexString = buffer.ToString();

Regards,
Thi - http://thith.blogspot.com
 
I forgot that PadLeft pads space if you did not specify paddingChar.
So use PadLeft(2, '0') instead.
 
Zeya,

Will GUID work for you cause the output is in hex? It is unique and very
very less chance of ever being repeated.

thanks,
Po
 
Pohihihi said:
and how this Int32.ToString("X") works??
you can not get HEX this way.

Have you actually tried it? int.ToString("X") specifies that you want
hex.

Here's the simplest way IMO of generating 16 random hex digits:

Random random = new Random();
string hex = random.Next().ToString("X8")+
random.Next().ToString("X8");

Note that you should actually have a single instance of Random used to
generate all your random numbers - don't create a new one each time, or
you'll get the same strings if you try to generate new ones within a
very short space of time.

Jon
 
Jon said:
Random random = new Random();
string hex = random.Next().ToString("X8")+
random.Next().ToString("X8");

Oops - just tried this, and while it will work, it never gives you a
digit over 7 for the first or ninth digit (because Random.Next() always
returns a non-negative number).

You could use Random.Next(int.MinValue, int.MaxValue) each time, which
would mean you could get every possibility *except* FFFFFFFF for each
section.

Alternatively, split it into four sections, using
random.Next(1<<16).ToString("X4") each time.

Jon
 
Thank you people for all your help.

GUID was one option I had considered and then the requirement changed.

The Random method is what I am going to try.

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top