Exitos
Exitos

Reputation: 29720

How do I convert this Hex to an Integer?

This is really confusing me. In a program for some unknown reason a counter is being stored to track the state between two databases. This is only essentially only an incremental counter.

The code stores this counter:

byte[] counter;

When it is stored in the database it gets rendered to a string like this...

0x00010471000001BF001F

I want to write an app that tells me if one is higher than the other and by how many by entering the two numbers. But I dont know how to convert these numbers into an integer representation.

Does anybody know what is going on and if this is possible?

Upvotes: 0

Views: 183

Answers (2)

Patrick McDonald
Patrick McDonald

Reputation: 65421

As the number is 20 hex digits (80 bit) it is too big to store in an int (32 bit) or a long (64 bit). You can use the BigInteger on .NET 4.0 or greater. (In .NET 4.0 you have to add a reference to System.Numerics.dll)

var bigint = new System.Numerics.BigInteger(counter)

As Øyvind pointed out, the above needs the byte array in little-endian order, i.e. new byte [] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } would evaluate to 1. Use Array.Reverse to work around this if necessary.

Since you have the number as a string, you should use BigInteger.Parse, note however you will have to trim the "0x" from the start

var bigint = System.Numerics.BigInteger.Parse("00010471000001BF001F",
                 System.Globalization.NumberStyles.HexNumber,
                 System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 4

Amir
Amir

Reputation: 724

based on this solution you can use

int intNumber = int.Parse(counter,system.Globalization.NumberStyles.HexNumber);

Upvotes: 0

Related Questions