Convert hexadecimal to integer

Asked

Viewed 816 times

2

I have this hexadecimal value "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 I’m doing wrong in conversion?

  • 1

    64 bits is required Padawan.

2 answers

4

  • I had already used this method, and gives this exception: "Value was either Too large or Too small for an Int32."

  • @Fabríciosimonealanamendes Make an F5. I updated the answer.

4


Missed you using the conversion base. There is also a problem because this number does not fit in a int, you need to 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));
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the 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. One should evaluate whether it is worth using the BigInteger even.

  • Visual returns the following error Error 1 Cannot implicitly Convert type 'long' to 'int'. An Explicit Conversion exists (are you Missing a cast?) Need to store the conversion in an integer type variable.

  • You have to wear one long for this, the hexadecimal number is too large to fit in a int. Either you work with smaller numbers or change the type of CodLibercao. I edited showing a smaller number.

  • I really need to work with this 18-character hexa, and it keeps giving error tando, ulong, long, int, Unit, "Input string was not in a correct format."

  • You can enter your full code. You saw in my answer that it works. http://answall.com/help/mcve

  • on console or Messagebox, do windowsform and store in a variable. To then appear textbox. On console I tested, in messagebox as well. But I need to convert into integer perform the calculation of this hexa with today’s date, and show in a textbox. I am using C#

  • Right I had forgotten that var can also be used in C#. thanks. Sorry for the failed act. var Hex = "E365A931A000000"; long Codrelease = Convert.Toint64(Hex,16);

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.