自个儿实现各种进制相互转换

www.MyException.Cn  网友分享于：2015-08-20  浏览：0次

ok, 直接进入主题。先说一下各进制转换的算法(百度一下也ok的)。

0.5 * 8 = 4.0 ; 也就是：4。

so,上面就是基本的转换过程，文字表达起来肯定没那么清晰，有兴趣的朋友可以百度，图文并茂，更好理解。

static string SystemConvertUseAPI(string value, int from, int to)
{
int temp = Convert.ToInt32(value, from);
return Convert.ToString(temp, to);
}

public static class SystemConvert
{
public static string ConvertValue(string value, int from, int to)
{
EnsureArguments(value, from, to);
char c = value[0];
string[] values = GetValues(value);
string result = string.Empty;
if (from == 10)
result = TenToOthers(values, to);
else if (to == 10)
result = OthersToTen(values, from);
else
result = OthersToOthers(values, from, to);

return c == '-' ? c.ToString() + result : result;
}

/// <summary>
/// 检查参数
/// </summary>
/// <param name="value"></param>
/// <param name="from"></param>
/// <param name="to"></param>
private static void EnsureArguments(string value, int from, int to)
{
if (value == null || value.Trim() == string.Empty)
throw new ArgumentNullException("value");
if (!(from == 10 || from == 2 || from == 8 || from == 16))
throw new ArgumentException("from 指定的基数不正确！");
if (!(to == 10 || to == 2 || to == 8 || to == 16))
throw new ArgumentException("to 指定的基数不正确！");

string pattern = string.Empty;
Regex regex = null;
if (from == 2)
pattern = @"^(\-|\+?)[01]+(.{0,1}[01]+)?\$";
else if (from == 8)
pattern = @"^(\-|\+?)[01234567]+(.{0,1}[01234567]+)?\$";
else if (from == 10)
pattern = @"^(\-|\+?)[0123456789]+(.{0,1}[0123456789]+)?\$";
else
pattern = @"^(\-|\+?)[0123456789|abcdef|ABCDEF]+(.{0,1}[0123456789|abcdef|ABCDEF]+)?\$";

regex = new Regex(pattern);
if (!regex.IsMatch(value))
throw new ArgumentException("源字符串不符合" + from.ToString() + "进制规范");
}

/// <summary>
/// 拆分字符串
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static string[] GetValues(string value)
{
value = value.Trim(new char[] { '+', '-', '0', '.' });
return value.Split(new char[] { '.' });
}

private static int Format16Char2Number(string c)
{
switch (c.ToUpper())
{
case "A":
return 10;
case "B":
return 11;
case "C":
return 12;
case "D":
return 13;
case "E":
return 14;
case "F":
return 15;
default:
return Convert.ToInt32(c);
}
}

private static string Format16Number2Char(int number)
{
switch (number)
{
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
default:
return number.ToString();
}
}

/// <summary>
/// 其它进制转换为10进制(位乘法)
/// </summary>
/// <param name="value"></param>
/// <param name="from"></param>
/// <returns></returns>
private static string OthersToTen(string[] values, int from)
{
string result = string.Empty;
string integer = values[0];
string temp = string.Empty;
int integerCurrent = 0;
int integerResult = 0;
int index = integer.Length - 1;
bool is16 = from == 16;
foreach (var c in integer)
{
temp = c.ToString();
integerCurrent = is16 ? Format16Char2Number(temp) : Convert.ToInt32(temp);
integerResult += integerCurrent * (int)Math.Pow((double)from, (double)index);
index--;
}

if (values.Length <= 1)
{
return integerResult.ToString();
}
else
{
string decimaler = values[1];
double decimalerCurrent = 0.0;
double decimalerResult = 0.0;
index = -1;
foreach (var c in decimaler)
{
temp = c.ToString();
decimalerCurrent = is16 ? Format16Char2Number(temp) : Convert.ToDouble(temp);
decimalerResult += decimalerCurrent * Math.Pow((from), (double)index);
index--;
}
return (integerResult + decimalerResult).ToString();
}
}

/// <summary>
/// 10进制转换为其它进制（辗转相除法)
/// </summary>
/// <param name="values"></param>
/// <param name="to"></param>
/// <returns></returns>
private static string TenToOthers(string[] values, int to)
{
int integerCurrent = Convert.ToInt32(values[0]);
int remainder = 1;
bool is16 = to == 16;
string integerResult = string.Empty;
while (integerCurrent > 0)
{
remainder = integerCurrent % to;
integerResult = (is16 ? Format16Number2Char(remainder) : remainder.ToString()) + integerResult;
integerCurrent = integerCurrent / to;
}
if (values.Length <= 1)
{
return integerResult;
}
else
{
double decimalerCurrent = Convert.ToInt32(values[1]) / Math.Pow(10.0, (double)values[1].Length);
int decimalerInt = 0;
double decimalerDec = decimalerCurrent;
string decimalerResult = string.Empty;
string[] strArr;
while (decimalerDec != 0)
{
decimalerCurrent = decimalerDec * to;
//拆分double,得到整数和小数部分
strArr = decimalerCurrent.ToString().Split(new char[] { '.' });
decimalerInt = Convert.ToInt32(strArr[0]);
if (strArr.Length > 1)
decimalerDec = Convert.ToDouble(strArr[1]) / (Math.Pow(10.0, (double)strArr[1].Length));
else
decimalerDec = 0;
decimalerResult += is16 ? Format16Number2Char(decimalerInt) : decimalerInt.ToString();
//这里默认精确到32位，可以加个参数指定
if (decimalerResult.Length > 32)
break;
}
return integerResult + "." + decimalerResult;
}
}

/// <summary>
/// 其它进制互转。以10进制为中间值即可
/// </summary>
/// <param name="values"></param>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
private static string OthersToOthers(string[] values, int from, int to)
{
string to10 = OthersToTen(values, from);
values = to10.Split(new char[] { '.' });
return TenToOthers(values, to);
}
}