I have made following coding to convert a hexa decimal to integer. [My algorithm]
private static void ConvertFromBase16(string value)
{
value = value.ToUpper();
int result = 0;
int incrementor = 0;
for (int i = value.Length-1; i >= 0; i-- )
{
char c = value[i];
char number;
if (c > 64)
{
number = (char)(c - 55); //Ascii character for A start from 65.in hex
//its 10, so i have subtracted 55 from it.
}
else
{
number = (char)(c - 48); //Ascii character for 0 is 48, so subtracting
//48
}
int n = (int) number;
result += (number* (int) Math.Pow(16 , incrementor));
incrementor++;
}
Console.WriteLine(result);
}
As you can see, in the above code I’ve used ascii characters for conversion than using traditional case conditions.
I’m quite a bit doubtful, whether this will work in all OS and create proper results.
Please can some one suggest me whether this is correct approach and wont be error prone?
PS:
I know, converting using .net default library method int.parse with globalization cultures. I want to do this manually in order to learn data structures concept. So please dont post anything handy from default .net library.
You could just use the characters themselves to check and subtract, being independent of the actual charset.
So instead of, for example
use
This way you let the framework/compiler do the conversation to an actual charset for you. This is the way this is usually done in C/C++ too.
In general with C# you don’t need to worry about your code working “in all OS”, because officially it will only run in Windows anyways. But if the default charset is ever changed then your code will break.