using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HexStringToInt
{
class Program
{
static void Main(string[] args)
{
int a = ConvertToInteger("1f");
Console.WriteLine("a: {0}", a);
}
static int ConvertToInteger(string input)
{
Hashtable hs = new Hashtable();
hs.Add("0", 0);
hs.Add("1", 1);
hs.Add("2", 2);
hs.Add("3", 3);
hs.Add("4", 4);
hs.Add("5", 5);
hs.Add("6", 6);
hs.Add("7", 7);
hs.Add("8", 8);
hs.Add("9", 9);
hs.Add("A", 10);
hs.Add("B", 11);
hs.Add("C", 12);
hs.Add("D", 13);
hs.Add("E", 14);
hs.Add("F", 15);
int result = 0;
int start = 0;
int sign = 1;
if (input[0] == '-')
{
start = 1;
sign = -1;
}
for (int i = start; i < input.Length; i++)
{
result = (result * 16) + (int) hs[input[i].ToString().ToUpper()];
}
return result * sign;
}
}
}
Monday, March 9, 2009
Subscribe to:
Post Comments (Atom)
1 comment:
will this way more efficient?
I've change the hashtable key to char, the perform char.toUpper instead of using toString().toUpper()
static int ConvertToInteger(string input)
{
Hashtable hs = new Hashtable();
hs.Add('0', 0);
hs.Add('1', 1);
hs.Add('2', 2);
hs.Add('3', 3);
hs.Add('4', 4);
hs.Add('5', 5);
hs.Add('6', 6);
hs.Add('7', 7);
hs.Add('8', 8);
hs.Add('9', 9);
hs.Add('A', 10);
hs.Add('B', 11);
hs.Add('C', 12);
hs.Add('D', 13);
hs.Add('E', 14);
hs.Add('F', 15);
int result = 0;
int start = 0;
int sign = 1;
if (input[0] == '-')
{
start = 1;
sign = -1;
}
for (int i = start; i < input.Length; i++)
result = (result * 16) + (int)hs[char.ToUpper(input[i])];
return result * sign;
}
Post a Comment