Check a string to see if all characters are hexadecimal values

Viewed 100479

What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?

Example

void Test()
{
    OnlyHexInString("123ABC"); // Returns true
    OnlyHexInString("123def"); // Returns true
    OnlyHexInString("123g"); // Returns false
}

bool OnlyHexInString(string text)
{
    // Most efficient algorithm to check each digit in C# 2.0 goes here
}
19 Answers

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);

In terms of programmer time, it's probably best to call your platform's string-to-integer parsing function (such as Java's Integer.parseInt(str, base)), and see if you get an exception. If you want to write it yourself, and potentially be more time/space-efficient...

Most efficient I suppose would be a lookup table on each character. You would have a 2^8 (or 2^16 for Unicode)-entry array of booleans, each of which would be true if it is a valid hex character, or false if not. The code would look something like (in Java, sorry ;-):

boolean lut[256]={false,false,true,........}

boolean OnlyHexInString(String text)
{
  for(int i = 0; i < text.size(); i++)
    if(!lut[text.charAt(i)])
      return false;
  return true;
}

This could be done with regular expressions, which are an efficient way of checking if a string matches a particular pattern.

A possible regular expression for a hex digit would be [A-Ha-h0-9], some implementations even have a specific code for hex digits, e.g. [[:xdigit:]].

Related