Reputation: 131
I'm trying to convert a string representing a hexadecimal value, for example "A0F3"
, into a hexadecimal or byte
value. I tryed to do something like this:
string text = "A0F3";
char[] chars = text.ToCharArray();
StringBuilder stringBuilder = new StringBuilder();
foreach(char c in chars)
{
stringBuilder.Append(((Int16)c).ToString("x"));
}
String textAsHex = stringBuilder.ToString();
Console.WriteLine(textAsHex);
But obviously I'm not converting the final value to a byte
value, I'm stuck.
I apprecciate your help.
Upvotes: 0
Views: 78
Reputation: 164341
Convert.ToInt32
has an overload that takes the base as a parameter.
Convert.ToInt32("A0F3",16)
should yield the desired result.
However, if you want to code it yourself as an exercise, the general algorithm is: Each character corresponds to a 4 bit value. Convert each character to it's value and create an integer by shifting bits left as you go. This could be a general algorithm, please don't use without adding bounds checking, 0x
prefix support, etc (And you really should be using the framework built-ins for production code) - but here goes:
public static int FromHexString(string hex)
{
int value = 0;
foreach (char c in hex.ToUpperInvariant().Trim())
{
var n = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
value = (value << 4) | n;
}
return value;
}
Upvotes: 1