Transformation from one position scale of notation to another
How can I transform from one scale of notation to another using my custom function by C#.
abstract string Convert(string value, string fromBase, string toBase);
value - string representation scale of notation in basic notation
fromBase - string represent the base of numeric
toBase - string representation the base of numeric which you must to transform
P.S. string which represents the base position scale开发者_如何学运维 of notation can include any symbols for represent numeral ascending order
For example
Value = “GSAK”
fromBase = “A,S,G,K” – four(4) is the base scale of notation (If write arabic figures: 0,1,2,3)
toBase= “0,1,2,3,4,5,6,7,8,9” – ten(10) is the base scale of notation
return value = “147”
I would first translate the input value to one of the numeric data types (i.e. long), and then encode into the target format. Draft implementation of a class to do the parsing and encoding (untested and certainly not optimal):
public class Formatter
{
List<char> symbols;
int base;
public Formatter(string format)
{
string[] splitted = format.Split(",");
symbols = splitted.Select(x => x[0]).ToList();
base = symbols.Size;
}
public long Parse(string value)
{
long result = 0;
foreach(char c in value)
{
long n = symbols.IndexOf(c);
result = result*base+n;
}
return result;
}
public string Encode(long value)
{
StringBuilder sb = new StringBuilder();
while(value>0)
{
long n = value % base;
value /= base;
sb.Insert(0, symbols[n]);
}
return sb.ToString();
}
}
精彩评论