Convert hexadecimal to integer

2

I have this value in hexadecimal "E365A931A000000".

I need to convert it to integer I'm using the following code.

string hex = "E365A931A000000";
CodLibercao = Convert.ToInt32(hex);

This code is giving me the following exception:

  

"Input string was not a correct format."

What am I doing wrong in the conversion?

    
asked by anonymous 03.03.2015 / 21:22

2 answers

4

You were not able to use the conversion base. There is also a problem because this number does not fit into a int , you must use a long ( Convert.ToInt64() ) to perform the conversion.

using System;
using System.Numerics;
using System.Globalization;

public class Program {
    public static void Main() {
        var hex = "E365A931A000000";
        Console.WriteLine(Convert.ToInt64(hex, 16));
        hex = "E365A931";
        Console.WriteLine(Convert.ToInt32(hex, 16));
        hex = "E365A931A000000000";
        Console.WriteLine(BigInteger.Parse(hex, NumberStyles.HexNumber));
    }
}

See working on dotNetFiddle .

I showed an example with a smaller number to fit in int . And a conversion that accommodates numbers of any size. You should evaluate whether it's worth using BigInteger .

    
03.03.2015 / 21:27
4

In fact converting from hexadecimal to integer requires the use of Parse , more specifically this format :

var codLiberacao = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);

I just did a test and this hex is too large for a 32-bit integer , then use long or Int64 for conversion:

var codLiberacao = Int64.Parse(hex, System.Globalization.NumberStyles.HexNumber);
    
03.03.2015 / 21:23