using System;
using System.Text;
namespace CSharpLab
{
public /* static */ class ConvertitoreNumerico
{
#region Simboli
static readonly char[] SIMBOLI_2 =
{'0', '1'};
static readonly char[] SIMBOLI_7 =
{'0', '1', '2', '3', '4', '5', '6'};
static readonly char[] SIMBOLI_10 =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
static readonly char[] SIMBOLI_16 =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
static readonly char[] SIMBOLI_26 =
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O','P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
#endregion
#region Metodi di conversione in stringa
public static string ConvertiInBase26(int number)
{
return ConvertiNumero(number, SIMBOLI_26);
}
public static string ConvertiInBase16(int number)
{
return ConvertiNumero(number, SIMBOLI_16);
}
public static string ConvertiInBase10(int number)
{
return ConvertiNumero(number, SIMBOLI_10);
}
public static string ConvertiInBase7(int number)
{
return ConvertiNumero(number, SIMBOLI_7);
}
public static string ConvertiInBase2(int number)
{
return ConvertiNumero(number, SIMBOLI_2);
}
public static string ConvertiNumero(int number, char[] symbols)
{
int b = symbols.Length;
int n = number;
StringBuilder sb = new StringBuilder();
while(n > 0)
{
int mod;
n = Math.DivRem(n, b, out mod);
sb.Insert(0, symbols[mod]);
}
return sb.ToString();
}
#endregion
#region Metodi di conversione da stringa
public static int ConvertiInNumeroDaBase26(string value)
{
return ConvertiInNumero(value, SIMBOLI_26);
}
public static int ConvertiInNumeroDaBase16(string value)
{
return ConvertiInNumero(value, SIMBOLI_16);
}
public static int ConvertiInNumeroDaBase10(string value)
{
return ConvertiInNumero(value, SIMBOLI_10);
}
public static int ConvertiInNumeroDaBase7(string value)
{
return ConvertiInNumero(value, SIMBOLI_7);
}
public static int ConvertiInNumeroDaBase2(string value)
{
return ConvertiInNumero(value, SIMBOLI_2);
}
public static int ConvertiInNumero(string value, char[] symbols)
{
int n = 0;
int sz = value.Length;
int b = symbols.Length;
for(int i = 0, j = sz - 1; i < sz; i++, j--)
{
char symbol = value[j];
int p = Array.BinarySearch(symbols, symbol);
if(p == -1)
{
throw new ArgumentException(
string.Format("Symbol not found: {0}", symbol), "value");
}
n += (int)Math.Pow(b, i) * p;
}
return n;
}
#endregion
}
}