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')
}
-
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');
From yjerem -
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."); }
From Jeff Yates -
What about
bool CharIsHex(char c) { c = Char.ToLower(c); return Char.IsDigit(c) || (c >= 'a' && c <= 'f'); }
From CMS -
Note that
Char.IsDigit()
returnstrue
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
through0xff19
. These glyphs look just like the ASCII characters0x30-0x39
, so if you're going to accept them you should also probably accept0xff21-0xff26
and0xff41-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.
From Michael Burr -
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())); } }
Jon Skeet : 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.
0 comments:
Post a Comment