0

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?

Exitos
  • 26,972
  • 35
  • 118
  • 168

2 Answers2

4

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);
Patrick McDonald
  • 59,808
  • 14
  • 95
  • 115
  • 1
    This is the best answer imo. But one caveat here, is that the BigInteger constructor needs the byte array in a little-endian order. If your byte array is not, then you need to use `Array.Reverse(counter);` first. – Øyvind Bråthen Nov 22 '12 at 10:19
  • thanks youve answered the question but do you also know any idea how I can use a string that the byte has been written to? A string like Ox00010471000001BF001F? – Exitos Nov 22 '12 at 10:19
0

based on this solution you can use

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

Community
  • 1
  • 1
Amir
  • 672
  • 1
  • 12
  • 34