Check a string to see if all characters are hexadecimal values
Something like this:
(I don't know C# so I'm not sure how to loop through the chars of a string.)
loop through the chars {
bool is_hex_char = (current_char >= '0' && current_char <= '9') ||
(current_char >= 'a' && current_char <= 'f') ||
(current_char >= 'A' && current_char <= 'F');
if (!is_hex_char) {
return false;
}
}
return true;
Code for Logic Above
private bool IsHex(IEnumerable<char> chars)
{
bool isHex;
foreach(var c in chars)
{
isHex = ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'));
if(!isHex)
return false;
}
return true;
}
public bool OnlyHexInString(string test)
{
// For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"
return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");
}
You can do a TryParse on the string to test if the string in its entirity is a hexadecimal number.
If it's a particularly long string, you could take it in chunks and loop through it.
// string hex = "bacg123"; Doesn't parse
// string hex = "bac123"; Parses
string hex = "bacg123";
long output;
long.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out output);
I use Int32.TryParse()
to do this. Here's the MSDN page on it.