Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

c# - 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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...