Search code examples
c#hexbigintegerradix

Convert a "big" Hex number (string format) to a decimal number (string format) without BigInteger Class


How to convert a "big" Hex number (in string format):

EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679

to a decimal number (in string format):

166089946137986168535368849184301740204613753693156360462575217560130904921953976324839782808018277000296027060873747803291797869684516494894741699267674246881622658654267131250470956587908385447044319923040838072975636163137212887824248575510341104029461758594855159174329892125993844566497176102668262139513

without using BigInteger Class (as my application should support machines without .NET Framework 4)?


Solution

  • Here's a quick-and-dirty implementation that can work with arbitrarily-large numbers. The aim of this implementation is simplicity, not performance; thus, it should be optimized drastically if it's to be used in a production scenario.

    Edit: Simplified further per Dan Byström's implementation of the inverse decimal-to-hex conversion:

    static string HexToDecimal(string hex)
    {
        List<int> dec = new List<int> { 0 };   // decimal result
    
        foreach (char c in hex)
        {
            int carry = Convert.ToInt32(c.ToString(), 16);   
                // initially holds decimal value of current hex digit;
                // subsequently holds carry-over for multiplication
    
            for (int i = 0; i < dec.Count; ++i)
            {
                int val = dec[i] * 16 + carry;
                dec[i] = val % 10;
                carry = val / 10;
            }
    
            while (carry > 0)
            {
                dec.Add(carry % 10);
                carry /= 10;
            }
        }
    
        var chars = dec.Select(d => (char)('0' + d));
        var cArr = chars.Reverse().ToArray();
        return new string(cArr);
    }