1

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.

4

4 回答 4

2

Do it manually!

http://www.permadi.com/tutorial/numDecToHex/

于 2008-10-21T08:29:40.803 回答
2

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]);
}
于 2008-10-21T08:55:20.160 回答
1

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.

于 2008-10-21T08:33:22.873 回答
1

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);
于 2008-10-21T08:39:45.277 回答