Convert a single hex character to its byte value in C#
Question
This will convert 1 hex character to its integer value, but needs to construct a (sub) string.
Convert.ToInt32(serializedString.Substring(0,1), 16);
Does .NET have a built-in way to convert a single hex character to its byte (or int, doesn't matter) value that doesn't involve creating a new string?
Solution
int value = "0123456789ABCDEF".IndexOf(char.ToUpper(sourceString[index]));
Or even faster (subtraction vs. array search), but no checking for bad input:
int HexToInt(char hexChar)
{
hexChar = char.ToUpper(hexChar); // may not be necessary
return (int)hexChar < (int)'A' ?
((int)hexChar - (int)'0') :
10 + ((int)hexChar - (int)'A');
}
OTHER TIPS
Correct me if im wrong but can you simply use
Convert.ToByte(stringValue, 16);
as long as the stringValue represents a hex number? Isnt that the point of the base paramter?
Strings are immutable, I dont think there is a way to get the substring byte value of the char at index 0 without creating a new string
Sure you can get the hex value without ever needing to create another string. I'm not sure what it'll really gain you, performance wise, but since you asked, here's what you've requested.
public int FromHex(ref string hexcode, int index)
{
char c = hexcode[index];
switch (c)
{
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
case 'a':
return 0xa;
case 'B':
case 'b':
return 0xb;
case 'C':
case 'c':
return 0xc;
case 'D':
case 'd':
return 0xd;
case 'E':
case 'e':
return 0xe;
case 'F':
case 'f':
return 0xf;
case '0':
default:
return 0;
}
}
}
If you know the hex value is only a byte then just convert to an Int32 and then cast
var b = (byte)(Convert.ToInt32(serializedString, 16));
Encoding.UTF8.GetBytes( serializedString.ToCharArray(), 0, 1)
Cheaper might be:
Encoding.UTF8.GetBytes( new char[]{ serializedString[0] }, 0, 1)
This will only add the interesting char to the char[] and not the entire string.