Nadesłany przez Tomasz Lubiński, 23 listopada 2006 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
systemy_cs/Systemy.cs:
//
// Konwersja z i na system dziesietny
//
// www.algorytm.org
// (c)2007 by Tomasz Lubinski
//
using System;
namespace systemy_cs
{
/// <summary>
/// Konwersja z i na system dziesietny.
/// </summary>
class Systemy
{
private static int MAX_BASE = 36;
private static String pattern = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// Convert number to given base
/// </summary>
/// <param name="n">number to convert</param>
/// <param name="newBase">base of result</param>
/// <returns>returns converted n or null if an error occurs</returns>
public static String convertTo(int n, int newBase)
{
String result = "";
//base is too big or too small
if ((newBase > MAX_BASE) || (newBase < 2))
return null;
//n is equal to 0, do not process, return "0"
if (n == 0)
return "0";
//process until n > 0
while (n>0)
{
result = pattern[n % newBase] + result;
n /= newBase;
}
return result;
}
/// <summary>
/// Returns value of character in a given base
/// </summary>
/// <param name="x">character to check</param>
/// <param name="baseOfX">base of x</param>
/// <returns>return value of x or -1 if an error occurs</returns>
private static int valueOf(char x, int baseOfX)
{
for (int i=0; i<baseOfX; i++)
{
if (x == pattern[i])
{
return i;
}
}
return -1;
}
/// <summary>
/// Convert n to decimal
/// </summary>
/// <param name="n">number to convert</param>
/// <param name="baseOfN">base of a given n</param>
/// <returns>returns converted n or 0 if an error occurs</returns>
public static int convertFrom(String n, int baseOfN)
{
int i, x;
int p = 1;
int result = 0;
//base is too big or too small
if ((baseOfN > MAX_BASE) || (baseOfN < 2))
return 0;
n = n.ToUpper();
for (i=n.Length-1; i>=0; i--)
{
x = valueOf(n[i], baseOfN);
if (x < 0)
{
return 0;
}
result += (x * p);
p *= baseOfN;
}
return result;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("3568 w systemie dwojkowym = " + convertTo(3568, 2));
Console.WriteLine("3568 w systemie trojkowym = " + convertTo(3568, 3));
Console.WriteLine("3568 w systemie osemkowym = " + convertTo(3568, 8));
Console.WriteLine("3568 w systemie szesnastkowym = " + convertTo(3568, 16));
Console.WriteLine("3568 w systemie dwudziestkowym = " + convertTo(3568, 20));
Console.WriteLine("100010010 w systemie dwojkowym to " + convertFrom("100010010", 2) + " w systemie dziesietnym");
Console.WriteLine("7542 w systemie ósemkowym to " + convertFrom("7542", 8) + " w systemie dziesietnym");
Console.WriteLine("E854 w systemie szesnastkowym to " + convertFrom("E854", 16) + " w systemie dziesietnym");
}
}
}

