Thursday, December 10, 2009

Wednesday, December 9, 2009

Printing numeric values as HEX

I sometimes need to print integer numeric values as a hexadecimal string for better reading and everytime I have to search about it with google.

So here is a collection of printing values as hexadecimal string.

The simpliest way is to use the IFormattable interface:
   1:  String.Format("{0:X02}", int.MaxValue);

Other ways with support of differend radix is to user Convert.ToString().
Radix could be 2, 8, 10, or 16.
   1:  Convert.ToString(int.MaxValue, 2);

From:
MSDN: Convert.ToString()
mikrocontroller.net


Are there any other ways? So let me know!

Monday, December 7, 2009

Advanced Stringreplace

While handling string data it's often needed to replace or cut a partial string. String.Replace is such a simple method to replace values in C#.

But what about if you have to deal with patterns to replace or manipulate partial string?

Here you have to go beyond String.Replace and deal with regular expressions.
If you have't heared about Regular Expressions, I suggest to read this articles about it:
and some tools to check you patterns against data:

And now, time for some excamples.

Assume you have a string like
   1:  string data = "52/00000012340056";
and have to replace the zeros after the slash.

Your regex could be the following
   1:  Regex regex = new Regex(@"0+");

but take care about the zeros within the numbers. So you have to extend you regex like this:
   1:  Regex regex = new Regex(@"^\d+/0+");

If you run this expression over the sample data, the result looks like this:
   1:  string result = regex.Replace(data, String.Empty);
   2:  // result == "12340056";

Missing the prefix?

Extend the expressions with some named groups and use the matching values:
   1:  Regex regex = new Regex(@"^(?<prefix>\d+/)(0+)");
   2:  string result = regex.Replace(data, "${prefix}"); 
   3:  // result == "52/12340056";


That's it!