Char.IsHex () in C #

Following this question , what would be the best way to write the Char.IsHex () function in C #. So far I have this, but I don't like:

bool CharIsHex(char c) {
    c = Char.ToLower(c);
    return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
+3
source share
7 answers

From my answer to the question you contacted:

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

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 that you can call him as if he were a member char.

char c = 'A';

if (c.IsHex())
{
   Console.WriteLine("We have a hex char.");
}
+18
source

, Char.IsDigit() true , ASCII 0x30 0x39.

, , true Char.IsDigit(): '0' '1' '2' '3' '4' '5' '6' '7' '8' '9'

" ", Char.IsDigit() true : 0xff10 0xff19. , ASCII 0x30-0x39, , , 0xff21-0xff26 0xff41-0xff46, , "A" - "F" "a" - .

, ASCII, , , 'a'.. 'f' 'A'.. 'F', ASCII.

, - :

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

, .

+7

There is another way to do this using string comparison.

bool IsHex(char c)
{
    return "0123456789ABCDEFabcdef".IndexOf(c) != -1;
}
+3
source

What about

bool CharIsHex(char c) {
    c = Char.ToLower(c);
    return Char.IsDigit(c) || (c >= 'a' && c <= 'f');
}
+2
source

Just use the .NET method:

char c = 'a';
System.Uri.IsHexDigit(c);
+2
source

You can use regular expressions in the 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()));
    }
}
-1
source

Source: https://habr.com/ru/post/1698618/


All Articles