设有一个数 A,比如 A=15 ,转为四进制数应当表示为33.
原理如下:
1.A除N,
2.A模N.
3.保存A模N的值。
4.循环1,2。直到 A除N的值等于0;
Code
class NumerationConverter
{
/// <summary>
/// 将十进制度数转为四进制
/// </summary>
/// <param name="src"></param>
/// <param name="N"></param>
/// <returns></returns>
public static string ConvertFromTen(int src ,int N)
{
Stack<int> strs = new Stack<int>();
int temp1 = src / N;
int temp2 = src % N;
while (temp1 > 0)
{
strs.Push(temp2);
temp2=temp1%N;
temp1 = temp1 / N;
}
strs.Push(temp2);
StringBuilder sb = new StringBuilder();
while (strs.Count > 0)
{
sb.Append(strs.Pop());
}
return sb.ToString();
}
}
class NumerationConverter
{
/// <summary>
/// 将十进制度数转为四进制
/// </summary>
/// <param name="src"></param>
/// <param name="N"></param>
/// <returns></returns>
public static string ConvertFromTen(int src ,int N)
{
Stack<int> strs = new Stack<int>();
int temp1 = src / N;
int temp2 = src % N;
while (temp1 > 0)
{
strs.Push(temp2);
temp2=temp1%N;
temp1 = temp1 / N;
}
strs.Push(temp2);
StringBuilder sb = new StringBuilder();
while (strs.Count > 0)
{
sb.Append(strs.Pop());
}
return sb.ToString();
}
}
单元测试如下:
Code
/// <summary>
///ConvertFromTen 的测试
///</summary>
[TestMethod()]
public void ConvertFromTenTest()
{
int src = 3;
string expected = "3";
string actual;
actual = NumerationConverter.ConvertFromTen(src,4);
Assert.AreEqual(expected, actual);
}
/// <summary>
///ConvertFromTen 的测试
///</summary>
[TestMethod()]
public void ConvertFromTenTest()
{
int src = 3;
string expected = "3";
string actual;
actual = NumerationConverter.ConvertFromTen(src,4);
Assert.AreEqual(expected, actual);
}