Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert a number larger than Int64 to HexaDecimal

Tags:

c#

.net

hex

int64

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.

like image 933
Salem Avatar asked Dec 09 '22 00:12

Salem


2 Answers

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.

like image 94
phoog Avatar answered Jan 02 '23 23:01

phoog


Perhaps:

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

Or

ulong l = 9407524828459565063;
var hex = l.ToString("X2");
like image 23
Magnus Avatar answered Jan 02 '23 23:01

Magnus