String Formatting

  • Thread starter Thread starter Saurabh
  • Start date Start date
S

Saurabh

This may be very silly question but I cannot find a way to convert a number
into a string representation which is an 8 digit hex value.

For example I want to convert a number -2147221503 into an 8 digit hex
number. In MFC I would have used the CString class and the format string of
"%08X" would have worked perfectly well. How do i achieve this in C#. I
tried using string ss = s.ToString("%08X"); where s is the number but this
gives me a string as "-%2147221503008X" which is not what I am looking for.
the static String.Format( ) method does not seem to work either.

Any inputs,

TIA,

--Saurabh
 
Saurabh said:
This may be very silly question but I cannot find a way to convert a number
into a string representation which is an 8 digit hex value.

For example I want to convert a number -2147221503 into an 8 digit hex
number. In MFC I would have used the CString class and the format string of
"%08X" would have worked perfectly well. How do i achieve this in C#. I
tried using string ss = s.ToString("%08X"); where s is the number but this
gives me a string as "-%2147221503008X" which is not what I am looking for.

Your mistake is assuming that the format specifiers in .NET are the
same as in C++. They're not.
the static String.Format( ) method does not seem to work either.

Yes it does - you're just not using it properly.

using System;

public class Test
{
static void Main()
{
string s = (-2147221503).ToString("x8");
Console.WriteLine (s);

Console.WriteLine (String.Format ("{0:x8}", -2147221503));
Console.WriteLine ("{0:x8}", -2147221503);
}
}
 
Thanks a lot!!

--Saurabh

Jon Skeet said:
for.

Your mistake is assuming that the format specifiers in .NET are the
same as in C++. They're not.


Yes it does - you're just not using it properly.

using System;

public class Test
{
static void Main()
{
string s = (-2147221503).ToString("x8");
Console.WriteLine (s);

Console.WriteLine (String.Format ("{0:x8}", -2147221503));
Console.WriteLine ("{0:x8}", -2147221503);
}
}
 
Back
Top