0

I have the following xml:

<RootLevel>
  <Level1 type="Integer" value="0x53494553"/>
  <Level1 type="Float" value="0x07"/>
  <Level1 type="Short" value="0x0002"/>
  <Level1 type="Short" value="0x0000"/>
<RootLevel>

Respect to this xml, i get the Type value and cast them with no problem. But when i try to parse the hexadecimal values with

Convert.ToInt32(node.Attributes["value"].Value)
or
Convert.ToInt32(node.Attributes["value"].Value,NumberStyles.HexNumber)
or
int.Parse(node.Attributes["value"].Value)
or
int.Parse(node.Attributes["value"].Value, NumberStyles.HexNumber)

It gives the following error:

Input string was not in a correct format.

In case i am trying to parse into integer but for every dataType it will be similar. Parsing for integer help is enough.

What am i missing here?

Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68

2 Answers2

2

Converting Hex string to Int in C#

For a hex literal that’s not prefixed you can quite easily convert it using int.Parse in C#:

string hex = "142CBD";
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);    // this returns 1322173

But as you’ve probably noticed, most hex literals are prefixed with 0x (e.g. “0x142CBD”) which would throw a FormatException if you try to parse it using the above code.

In order to parse a 0x prefixed hex literal you need to use the Convert.ToInt32(string value, int fromBase) method instead:

string prefixedHex = "0x142CBD";
int intValue = Convert.ToInt32(prefixedHex , 16);     // this works, and returns 1322173
Tapas Thakkar
  • 845
  • 8
  • 19
1

You have to remove start '0', 'x' chars. Try this:

if(int.TryParse(node.Attributes["value"].Value.Remove(0, 2), NumberStyles.HexNumber)
{
     // your code
}
daniell89
  • 1,832
  • 16
  • 28