Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format() Hex with leading zero doesn't work for second argument

I'm facing a weird issue with String.Format(). I need to format two hexadecimal numbers with leading zeroes to pad up to 8 digits. However, it works only for the first argument ({0:X8}). For the second argument ({1:X8}), only "X8" is printed.

This is my code:

public struct DataDirectory
{
    public uint VirtualAddress
    {
        get;
        internal set;
    }

    public uint Size
    {
        get;
        internal set;
    }

    public override string ToString()
    {
        return String.Format("{{VirtualAddress=0x{0:X8},Size=0x{1:X8}}}", VirtualAddress, Size);
    }
}

The debugger output prints this:

Debugger output

EDIT: It seems to work if I remove the curly braces at the start and end of the format string, but then I'm missing those in the strings returned from ToString() (the debugger still adds those to the QuickWatch window):

return String.Format("VirtualAddress=0x{0:X8},Size=0x{1:X8}", VirtualAddress, Size);

Is it possible to format two hexadecimal numbers with String.Format()?

like image 835
Ray Avatar asked Feb 28 '15 11:02

Ray


1 Answers

Be careful with all those closing braces }}}. You can use a separate format item for it, as in Size=0x{1:X8}{2}. So:

String.Format("{{VirtualAddress=0x{0:X8},Size=0x{1:X8}{2}", 
  VirtualAddress, Size, "}"
  )

The problem with {1:X8}}} is that it is not clear which double }} is an escaped }, and which single } is closing the item. The parser actually called Size.ToString("X8}") which was not what you intended.

Now you are going in that direction, maybe do:

String.Format("{2}VirtualAddress=0x{0:X8},Size=0x{1:X8}{3}", 
  VirtualAddress, Size, "{", "}"
  )
like image 138
Jeppe Stig Nielsen Avatar answered Oct 11 '22 10:10

Jeppe Stig Nielsen