4

I am trying to convert a big number(ex: 9407524828459565063) to Hexadecimal(ex: 828E3DFD00000000) in C#.

The problem is that the number is larger than Int64's max value.

i looked up everywhere and couldn't find a working solution.

Any help over here?

Thank you.

Salem
  • 311
  • 2
  • 12

3 Answers3

9

I would use the System.Numerics.BigInteger class to do this. The exact solution depends on the format in which you have this number: string, double, other.

If string (s):

var bigInt = BigInteger.Parse(s);
var hexString = bigInt.ToString("x");

If double (d):

var bigInt = new BigInteger(d);
var hexString = bigInt.ToString("x");

... etcetera.

phoog
  • 42,068
  • 6
  • 79
  • 117
  • 1
    BigInteger was introduced in .Net 4.0, so if you can use it then you can convert [BigInteger to Hexadeximal](http://stackoverflow.com/questions/4988858/biginteger-to-hexadeximal) – Erik Philips Apr 18 '12 at 19:11
  • I discovered `BigInteger.ToString("X")` sometimes adds a leading zero. I have created extension methods to convert to hex, binary and octal (see: http://stackoverflow.com/questions/14048476/#15447131) which do not include any leading zero. – Kevin P. Rice Mar 16 '13 at 08:30
3

Perhaps:

BigInteger b = 9407524828459565063;
var hex = b.ToString("X2");

Or

ulong l = 9407524828459565063;
var hex = l.ToString("X2");
Magnus
  • 45,362
  • 8
  • 80
  • 118
2

If you are using .NET 4.0, you might have a look at the BigInteger class:

http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx

  BigInteger bi = new BigInteger();
  bi = 9407524828459565063;
  string bix = bi.ToString("X");
wageoghe
  • 27,390
  • 13
  • 88
  • 116