17

I have an integer variable with max value of 9999.

I can convert to fixed length string (4-characters):

value.ToString("0000");

and I can convert it to hex:

value.ToString("X");

I want to convert it to a hex string of four characters (padded with 0 at the left if the value is converted to less than four digits hex value). I tried the following which didn't work.

value.ToString("0000:X");

OK, I can check the length of hex string and pad left with zeros.

But is there any straightforward way?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Liton
  • 1,398
  • 2
  • 14
  • 27

3 Answers3

35

Use a number after the X format specifier to specify the left padding : value.ToString("X4")

Julien Lebosquain
  • 40,639
  • 8
  • 105
  • 117
9
String.Format( "{0:X2}", intValue)
Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
-2

Here is another method, You can define a function and pass it 2 values, one the actual number and the second is the max length to fix. i.e.

public string FixZero(string str, int maxlength)
{
    string zero = "000000000000000000000000000000000000000";
    int length = str.Length;
    int diff = maxlength- length;
    string z = zero.Substring(1, diff);
    z = z + str;
    return z;
}

you need integers in the format 0012, FixZero("12", 4) or for 0001234, FixZero("1234", 7)

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Sharp Coders
  • 458
  • 5
  • 7
  • I notified you [back on Nov 5](http://stackoverflow.com/questions/4011572/how-to-load-data-using-jquery-and-json/13238275#comment18035497_13238275) about the requirement that links to your own site contain a disclosure from you, yet you have failed to do so, again. – Andrew Barber Dec 04 '12 at 21:17