用堆栈实现十进制向其它进制间的转换
对于数字系统中进制间的转换,堆栈无疑是最好的选择,也是最能体现堆栈好处的地方。
以下是我用C#写的一个简单实现十进制数向2,8,16进制间的转换:
(当然,CLR还有更简单的方法,那就是Convert.ToString(int value, int toBase),value是需要转换的十进制数,toBase是将要转换的进制类型,2, 8或16进制)
以下是我用C#写的一个简单实现十进制数向2,8,16进制间的转换:
(当然,CLR还有更简单的方法,那就是Convert.ToString(int value, int toBase),value是需要转换的十进制数,toBase是将要转换的进制类型,2, 8或16进制)
namespace CRLDemo
{
class Program
{
static void Main(string[] args)
{
try
{
NumberSystemUtil.ConvertDecimal(31, Scale.Hexadecimal);
//Console.WriteLine(Convert.ToString(31, 16));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadLine();
}
}
}
public class NumberSystemUtil
{
public static void ConvertDecimal(int dec, Scale scale)
{
Stack<int> stack = new Stack<int>();
while (dec > 0)
{
stack.Push(dec % (int)scale);
dec = dec / (int)scale;
}
while (stack.Count > 0)
{
if (scale == Scale.Hexadecimal)
Console.Write(stack.Pop().ToString("x"));
else
Console.Write(stack.Pop());
}
}
}
public enum Scale
{
Hexadecimal = 16,
Octal = 8,
Binary = 2
}
}
{
class Program
{
static void Main(string[] args)
{
try
{
NumberSystemUtil.ConvertDecimal(31, Scale.Hexadecimal);
//Console.WriteLine(Convert.ToString(31, 16));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadLine();
}
}
}
public class NumberSystemUtil
{
public static void ConvertDecimal(int dec, Scale scale)
{
Stack<int> stack = new Stack<int>();
while (dec > 0)
{
stack.Push(dec % (int)scale);
dec = dec / (int)scale;
}
while (stack.Count > 0)
{
if (scale == Scale.Hexadecimal)
Console.Write(stack.Pop().ToString("x"));
else
Console.Write(stack.Pop());
}
}
}
public enum Scale
{
Hexadecimal = 16,
Octal = 8,
Binary = 2
}
}