Convert Hex to Long and Decimal

Question

• Hi there,

I am wondering if there is a ready method I can use to convert a Hex number (written as a string) to Long and/or Decimal. I can do it by going thru the string backwards, converting chars to God knows what, multiplying by the base(16) times position, adding the results, ect, ect, etc.

Still I am wondering if there is a C# method that does it.

There are methods in Microsoft.VisualBasic namespace but I could not get them in my Intellisense at all.

Thanks.

Tuesday, January 22, 2008 5:18 PM

• How to use the Int32.Parse method to convert the string representation of a hexadecimal integer to a decimal integer by using Visual C# .NET

Tuesday, January 22, 2008 5:24 PM

• How to use the Int32.Parse method to convert the string representation of a hexadecimal integer to a decimal integer by using Visual C# .NET

Tuesday, January 22, 2008 5:24 PM
•  H. (冬) Tony wrote:

How to use the Int32.Parse method to convert the string representation of a hexadecimal integer to a decimal integer by using Visual C# .NET

Thank you,

This is how far I got on my onw but I am getting this exception:

Code Block

private void convertHexToDateTime ( )

{

if (this.txtBoxINPUTS.Text != String.Empty)

{

Int64 num = Int64.Parse ( this.txtBoxINPUTS.Text.Trim ( ), System.Globalization.NumberStyles.HexNumber );

long numb = (long)Convert.ToDecimal ( num );

this.rtfFrontPage.Text = Convert.ToString ( Convert.ToDateTime ( numb ) );

}

}

It crashes at the last statement and the error message is:

Invalid cast from 'Int64' to 'DateTime'???

The value I put in is Long and I verified it. typeof (numb) = System.Long with input value = "4549b5b0"

Thanks.

Tuesday, January 22, 2008 6:04 PM
• that's exactly what it says.

Convert.ToDateTime(num); is invalid cast.

the following works:

Int64 num = Int64.Parse("FFFFF", System.Globalization.NumberStyles.HexNumber);

long numb = Convert.ToInt64(num); //no need to convert to Decimal then to long

DateTime dt = DateTime.FromBinary(numb);

Tuesday, January 22, 2008 6:10 PM
• long IS a Int64, long is just the primitive representation for Int64 and that is not why you are having problems. You are having problems because this "long" does not represent a valid DateTime type.

Using the FromBinary is a way around, but still probably not a valid DateTime representation and you will get (1/1/0001 00:00:00) for "FFFFF" and for most other Hex values.

You will successfully represent a DateTime in Hex in a case like this:

Code Block

long longint = Int64.Parse("88CA2B3C1D25971C", System.Globalization.NumberStyles.HexNumber);

DateTime dt = DateTime.FromBinary(longint);

MessageBox.Show(dt.ToString());

Regards,

Fábio

Tuesday, January 22, 2008 6:37 PM
•

can't system.convert be used to do the desired functionality??

Tuesday, January 22, 2008 6:44 PM
• Thank you Fabio and Tony as well.

Tuesday, January 22, 2008 6:56 PM