2005 August

7. February 2012

Parse hexadecimal values

Sometimes you need to parse hexadecimal strings to int values. I searched a while for the correct answer. You may use

Byte.Parse(string, NumberStyles.HexNumber);  

As always, Parse will throw an exception (ArgumentNullException, FormatException and OverflowException), if the conversion fails. There are two options of NumberStyle you may use:

AllowHexSpecifier: Indicates that the numeric string represents a hexadecimal value. Valid hexadecimal values include the numeric digits 0-9 and the hexadecimal digits A-F and a-f. Hexadecimal values can be left-padded with zeros. Strings parsed using this style are not permitted to be prefixed with "0x".

HexNumber: Indicates that the AllowLeadingWhite, AllowTrailingWhite, and AllowHexSpecifier styles are used. This is a composite number style.

Convert vs. Parse

There are at least two ways to convert a standard string type to an value type:

Convert.ToInt32

and

Int32.Parse

These two ways seem to be identical, but there aren’t. I used Lutz Reflector to show the differences:

Int32.Parse calls

public static int Parse(string s, NumberStyles style, IFormatProvider provider)
{
  NumberFormatInfo info1 = NumberFormatInfo.GetInstance(provider);
       NumberFormatInfo.ValidateParseStyle(style);
       return Number.ParseInt32(s, style, info1);
}

and Number.ParseInt32 is defined as InternalCall:

[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int ParseInt32(
string
s, NumberStyles style, NumberFormatInfo info);

Here is the code for Convert.ToInt32(string)

public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}

return int.Parse(value); }

Here you see the difference: Convert checks, if the argument is null and returns 0 in this case, instead of directly throwing an exception. If you don’t need this behavior, calling Int32.Parse is a (little bit) faster than calling Convert.ToInt32. Same is true for the hundred other Xxx.Parse and Convert.Xxx calls.

In addition: we should better use int.Parse instead of int32.parse. Do you want to now the reason? Read Clemens Vasters article.

Die Wahl 2005 in Bildern

Der Wahlkampf 2005 hat begonnen. Am Montag den 15. August 2005 besuchte uns der Bundeskanzler Gerhard Schröder (SPD) auf dem Jenaer Markplatz. Mit dabei waren der Thüringer SPD-Landeschef Christoph Matschie und der SPD-Direkt-Kandidat Volker Blumentritt sowie Brandenburgs Ministerpräsident Matthias Platzeck. Der Marktplatz war mit 6500 Menschen gut gefüllt und die Sicherheitsvorkehrungen äußerst aufwendig. Die wenigen Protest-Stimmen der JU begenete Schröder spontan und humorvoll. Die Bilder befinden sich in der Galerie.
Am Donnerstag den 18. August besuchte auch der Umweltminister Jürgen Trittin (Bündnis 90/Die Grünen) auf dem Holzmarkt. Ein kleines Publikum horchte der über eine Stunde langen Rede Trittins. Auch hier befinden sich die Bilder in der Galerie.