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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…