Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char.IsHex() in C#

Tags:

c#

algorithm

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')
}
like image 223
Guy Avatar asked Oct 23 '08 04:10

Guy


People also ask

How to check if a number is hex in C?

The isxdigit() function checks whether a character is a hexadecimal digit character (0-9, a-f, A-F) or not. The function prototype of isxdigit() is: int isxdigit( int arg );

What does Isxdigit return?

RETURN VALUE The isxdigit() function shall return non-zero if c is a hexadecimal digit; otherwise, it shall return 0.

What is hexadecimal in C?

In C programming language, a hexadecimal number is a value having a made up of 16 symbols which have 10 standard numerical systems from 0 to 9 and 6 extra symbols from A to F. In C, the hexadecimal number system is also known as base-16 number system.

What is Isxdigit?

isxdigit() function in C programming language checkes that whether the given character is hexadecimal or not. isxdigit() function is defined in ctype. h header file.


2 Answers

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.");
}
like image 169
Jeff Yates Avatar answered Sep 22 '22 02:09

Jeff Yates


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');
like image 37
Paige Ruten Avatar answered Sep 22 '22 02:09

Paige Ruten