ToString()

G

Guest

in C/C++ I can use printf("%0.2X",t) to add mack the output wit to parameter,
for example if t = 0xA after printf I will get 0x0A.
How can I do that in C#.
I want to print a hexa number but to be 4 carecters 0x000A insted of 0xA.
and also I want to print a bin number but to be 8 carecters 00001010 insted of 0xA = (0xA).ToString("B") ???????.
 
A

adnan boz

Hi,
I didn't see anything like this on c#, even not on numeric format stings,
But you can try this below for hex, it will give the same result, or you
could take a deep look at Regexp maybe someone did it before.

string out = "0x" + val.ToString("X").PadLeft(4,'0');


Good Luck
Adnan

in C/C++ I can use printf("%0.2X",t) to add mack the output wit to parameter,
for example if t = 0xA after printf I will get 0x0A.
How can I do that in C#.
I want to print a hexa number but to be 4 carecters 0x000A insted of 0xA.
and also I want to print a bin number but to be 8 carecters 00001010
insted of 0xA = (0xA).ToString("B") ???????.
 
M

Mike Kitchen

Hi

The following code shows an example console application.

/* ---- start of code ---- */
using System;

class hexConversion
{
public static void Main()
{
int myValue = 0;

while( myValue != -1 )
{
Console.Write( "Enter a real number or -1 to exit: " );
myValue = Convert.ToInt32( Console.ReadLine() );

if( myValue != -1 )
{
Console.WriteLine( "Number entered is : {0}", myValue );
Console.WriteLine( "Hex equivalent is : {0:x4}", myValue ); // will
add leading zeros to give four digit answer
Console.WriteLine( "" );
}
}

// Here to stop app from closing
Console.WriteLine( "\n\nPress Return to exit." );
Console.Read();
}
}
/* ---- end of code ---- */

I will add this to my snippets page
http://www.publicjoe.f9.co.uk/csharp/snip/snip017.html

Hope this helps

Publicjoe
C# Tutorial at http://www.publicjoe.f9.co.uk/csharp/tut.html
C# Snippets at http://www.publicjoe.f9.co.uk/csharp/snip/snippets.html
C# Ebook at http://www.publicjoe.f9.co.uk/csharp/samples/ebook.html

in C/C++ I can use printf("%0.2X",t) to add mack the output wit to parameter,
for example if t = 0xA after printf I will get 0x0A.
How can I do that in C#.
I want to print a hexa number but to be 4 carecters 0x000A insted of 0xA.
and also I want to print a bin number but to be 8 carecters 00001010
insted of 0xA = (0xA).ToString("B") ???????.
 

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

Top