2

I want to generate a 4 character hex number.

To generate a hex number you can use

string.format("{0:X}", number) 

and to generate a 4 char string you can use

string.format("{0:0000}", number)

Is there any way to combine them?

dcarneiro
  • 7,060
  • 11
  • 51
  • 74
  • possible duplicate of [How to convert an integer to fixed length hex string in c#](http://stackoverflow.com/questions/5000966/how-to-convert-an-integer-to-fixed-length-hex-string-in-c) – Henrik Feb 24 '11 at 10:54
  • my bad. didn't found the original post – dcarneiro Feb 24 '11 at 10:58

2 Answers2

5

I'm assuming you mean: 4-digit hexadecimal number.

If so, then yes:

string.Format("{0:X4}", number)

should do the trick.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
4

Have you tried:

string hex = string.Format("{0:X4}", number);

? Alternatively, if you don't need it to be part of a composite pattern, it's simpler to write:

string hex = number.ToString("X4");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194