tags:

views:

492

answers:

5
+1  Q: 

Char.IsHex() in C#

Following on from this question what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:

bool CharIsHex(char c) {
    c = Char.ToLower(c);
    return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
+4  A: 

From my answer to the question you linked to:

bool is_hex_char = (c >= '0' && c <= '9') ||
                   (c >= 'a' && c <= 'f') ||
                   (c >= 'A' && c <= 'F');
yjerem
+8  A: 

You can write it as an extension method:

public static class Extensions
{
   public static bool IsHex(this char c)
   {
      return   (c >= '0' && c <= '9') ||
               (c >= 'a' && c <= 'f') ||
               (c >= 'A' && c <= 'F');
   }
}

This means you can then call it as though it were a member of char.

char c = 'A';

if (c.IsHex())
{
   Console.WriteLine("We have a hex char.");
}
Jeff Yates
+2  A: 

What about

bool CharIsHex(char c) {
    c = Char.ToLower(c);
    return Char.IsDigit(c) || (c >= 'a' && c <= 'f');
}
CMS
+3  A: 

Note that Char.IsDigit() returns true for many more code points than just the digits in the ASCII range 0x30 to 0x39.

For example the Thai digit characters that return true from Char.IsDigit(): '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'

Also there are the 'Full width' characters that Char.IsDigit() returns true for: 0xff10 through 0xff19. These glyphs look just like the ASCII characters 0x30-0x39, so if you're going to accept them you should also probably accept 0xff21-0xff26 and 0xff41-0xff46 which look just like 'A'-'F' and 'a'-'f'.

If you're going to support digits that are outside of the ASCII range, your users might expect that you to support glyphs that correspond to Latin 'a'..'f' and 'A'..'F' that exist in other scripts outside of the ASCII range.

Personally, I think I'd stick with something more like:

        bool isHexChar = ('0' <= c) && (c <= '9') ||
                         ('a' <= c) && (c <= 'f') ||
                         ('A' <= c) && (c <= 'F');

Which I think would be potentially less surprising to people.

Michael Burr
A: 

You can use regular expressions in an extension function:

using System.Text.RegularExpressions;
public static class Extensions
{
    public static bool IsHex(this char c)
    {

        return (new Regex("[A-Fa-f0-9]").IsMatch(c.ToString()));
    }
}
A regex seems pretty heavy-weight for a test as simple as this - and in particular creating a new regular expression each time is going to be performance killer.
Jon Skeet