Sign in to follow this  
TANSTAAFL

Leading 0s in Hex Value, C# Style

Recommended Posts

TANSTAAFL    1160
After searching the Docs on this, I still can't figure out how to make my hex values pad with leading zeros using System.Console.WriteLine. I've got it ALMOST doing what I want with:
System.Console.WriteLine("D={0,4:X}", myMachine.Regs.D.Unsigned);

This, however, pads with spaces, not zeros, which isn't nearly "machine registery" enough for my purposes. The c# docs tell me all about formatting phone numbers, dollar amounts, and date/time values, but the only thing it tells me about formatting hex values is that I use "X". Other information: Using VC# Express 2005, making a console app. tia

Share this post


Link to post
Share on other sites
kSquared    1356
The alignment specifier for String.Format always pads with whitespace. If you want non-whitespace, you can write a custom IFormatProvider instead.

A better solution is to convert the value you want with the format provider first, then pad as needed. To get a string that pads with non-whitespace characters, use the PadLeft() or PadRight() methods of String.

Example:

Console.WriteLine("47 in 2-byte hexadecimal, padded to 10 characters total:");
Console.WriteLine("|0123456789|\n|{0,10}|", 47.ToString("X").PadLeft(4, '0'));


produces the output

47 in 2-byte hexadecimal, padded to 10 characters total:
|0123456789|
| 002F|


Notice how the format string "X" moved into the ToString() method and out of the first WriteLine parameter. We converted "47" to a string value using a hex format specifier (the "X"). Then we padded it on the left to 4 characters with zeroes. Finally, Console.WriteLine() pads it to 10 characters using whitespace.

To recap, s.PadLeft(m, n) pads s on the left with m - s.Length() instances of n (unless this is a negative number, in which case it doesn't do any padding). In other words, the format specifier "{0,p:q}" is more or less equivalent to [argument0].ToString("q").PadLeft(p).

hope that helps,

Share this post


Link to post
Share on other sites
TANSTAAFL    1160
while i appreciate your help, k2, it turns out that {0:X4} seems indeed to work, and boy am I glad that it does and I don't have to do the formatter way.

Share this post


Link to post
Share on other sites
kSquared    1356
Quote:
Original post by TANSTAAFL
while i appreciate your help, k2, it turns out that {0:X4} seems indeed to work, and boy am I glad that it does and I don't have to do the formatter way.

All's well that ends well! :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this