Convert hexadecimal to integer

I have this value in hex "E365A931A000000".

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

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

This code is sending me the following exception:

" Input string was not in a correct format."

What am I doing wrong in conversion?

Author: Maniero, 2015-03-03

2 answers

Missed you to use the conversion base. There is also a problem because this number does not fit in a int, one must use a long (Convert.ToInt64()) to perform the conversion.

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

See working on ideone. And no .NET Fiddle. Also I put on GitHub for future reference .

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

 4
Author: Maniero, 2020-09-21 16:14:40

Actually converting hexadecimal to integer requires the use of Parse, more specifically this format :

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

Only I did a test and this hexadecimal is too big for a 32-bit integer, so use long or Int64 for conversion:

var codLiberacao = Int64.Parse(hex, System.Globalization.NumberStyles.HexNumber);
 4
Author: Leonel Sanches da Silva, 2015-03-03 20:23:58