DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

How can I Convert a Big decimal number to Hex in C# (Eg : 588063595292424954445828)

StackOverflow https://stackoverflow.com/questions/221154

Question

The number is bigger than int & long but can be accomodated in Decimal. But the normal ToString or Convert methods don't work on Decimal.

Solution

I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.)

static string ConvertToHex(decimal d)
{
    int[] bits = decimal.GetBits(d);
    if (bits[3] != 0) // Sign and exponent
    {
        throw new ArgumentException();
    }
    return string.Format("{0:x8}{1:x8}{2:x8}",
        (uint)bits[2], (uint)bits[1], (uint)bits[0]);
}

OTHER TIPS

I've got to agree with James - do it manually - but don't use base-16. Use base 2^32, and print 8 hex digits at a time.

I guess one option would be to keep taking chunks off it, and converting individual chunks? A bit of mod/division etc, converting individual fragments...

So: what hex value do you expect?

Here's two approaches... one uses the binary structure of decimal; one does it manually. In reality, you might want to have a test: if bits[3] is zero, do it the quick way, otherwise do it manually.

    decimal d = 588063595292424954445828M;
    int[] bits = decimal.GetBits(d);
    if (bits[3] != 0) throw new InvalidOperationException("Only +ve integers supported!");
    string s = Convert.ToString(bits[2], 16).PadLeft(8,'0') // high
            + Convert.ToString(bits[1], 16).PadLeft(8, '0') // middle
            + Convert.ToString(bits[0], 16).PadLeft(8, '0'); // low
    Console.WriteLine(s);

    /* or Jon's much tidier: string.Format("{0:x8}{1:x8}{2:x8}",
            (uint)bits[2], (uint)bits[1], (uint)bits[0]);  */

    const decimal chunk = (decimal)(1 << 16);
    StringBuilder sb = new StringBuilder();
    while (d > 0)
    {
        int fragment = (int) (d % chunk);
        sb.Insert(0, Convert.ToString(fragment, 16).PadLeft(4, '0'));
        d -= fragment;
        d /= chunk;
    }
    Console.WriteLine(sb);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow