Check the string to see if all characters are hexadecimal values

What is the most efficient way in C # 2.0 to check every character in a string and return true if 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 } 
+41
c #
Oct 21 '08 at
source share
19 answers
 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"); } 
+55
21 Oct '08 at 22:56
source share

Something like that:

(I don't know C #, so I'm not sure how to scroll line by line.)

 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; 

The code for the 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; } 
+63
Oct 21 '08 at 22:55
source share

You can do a TryParse in a string to check if the string in its entirity is a hexadecimal number.

If this is a particularly long string, you can take it in pieces and go 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); 
+24
Oct 21 '08 at 22:55
source share

I am using Int32.TryParse() for this. Here is the MSDN page .

+7
Oct 21 '08 at 22:51
source share

Here is the LINQ yjerem version above:

 private static bool IsValidHexString(IEnumerable<char> hexString) { return hexString.Select(currentCharacter => (currentCharacter >= '0' && currentCharacter <= '9') || (currentCharacter >= 'a' && currentCharacter <= 'f') || (currentCharacter >= 'A' && currentCharacter <= 'F')).All(isHexCharacter => isHexCharacter); } 
+7
Apr 25 '11 at 17:21
source share

Publishing the VB.NET version is Jeremy's answer because I came here looking for that version. It should be easy to convert it to C #.

 ''' <summary> ''' Checks if a string contains ONLY hexadecimal digits. ''' </summary> ''' <param name="str">String to check.</param> ''' <returns> ''' True if string is a hexadecimal number, False if otherwise. ''' </returns> Public Function IsHex(ByVal str As String) As Boolean If String.IsNullOrWhiteSpace(str) Then _ Return False Dim i As Int32, c As Char If str.IndexOf("0x") = 0 Then _ str = str.Substring(2) While (i < str.Length) c = str.Chars(i) If Not (((c >= "0"c) AndAlso (c <= "9"c)) OrElse ((c >= "a"c) AndAlso (c <= "f"c)) OrElse ((c >= "A"c) AndAlso (c <= "F"c))) _ Then Return False Else i += 1 End If End While Return True End Function 
+4
Nov 06 2018-11-11T00:
source share

Regular expression is not very effective in better times. The most effective would be to use a simple for loop to search the characters of a string and break up the first found invalid.

However, this can be done very succinctly with LINQ :

 bool isHex = myString.ToCharArray().Any(c => !"0123456789abcdefABCDEF".Contains(c)); 

I cannot vouch for efficiency since LINQ is LINQ, but Any () should have a pretty well optimized compilation scheme.

+4
Jan 27 '13 at 0:39
source share

What about:

bool isHex = text.All("0123456789abcdefABCDEF".Contains);

This basically says: check to see if all characters in the text string in the string are valid hexadecimal values.

Which one is the easiest and most readable solution.

(don't forget to add using System.Linq; )

EDIT:
Just noticed that Enumerable.All() is only available with .NET 3.5.

+4
Apr 3 '15 at 21:11
source share

In terms of performance, the fastest is likely to simply list the characters and perform a simple comparison check.

 bool OnlyHexInString(string text) { for (var i = 0; i < text.Length; i++) { var current = text[i]; if (!(Char.IsDigit(current) || (current >= 'a' && current <= 'f'))) { return false; } } return true; } 

To really find out which method is the fastest, although you need to do profiling.

+3
Nov 06 2018-11-11T00:
source share
  //Another workaround, although RegularExpressions is the best solution boolean OnlyHexInString(String text) { for(int i = 0; i < text.size(); i++) if( !Uri.IsHexDigit(text.charAt(i)) ) return false; return true; } 
+2
Aug 26 '13 at 20:57
source share

In terms of programmer time, it is probably best to name a string-chain parsing function (e.g. Java Integer.parseInt (str, base)) and see if you get an exception. If you want to write it yourself and potentially have more time / space-efficiency ...

The most effective, I assume, will be a lookup table for each character. You will have a 2 ^ 8 (or 2 ^ 16 for Unicode) -entry array of booleans, each of which will be true if it is a valid hexadecimal character, or false if not. The code will look something like this (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; } 
+1
Oct 21 '08 at
source share

This can be done using regular expressions, which are an effective way to check if a string matches a particular pattern.

A possible regular expression for a hexadecimal digit would be [A-Ha-h0-9], some implementations even have a specific code for hexadecimal digits, for example. [[: Xdigit:]].

0
Oct 21 '08 at 23:02
source share

You can expand the string and char using the following command:

  public static bool IsHex(this string value) { return value.All(c => c.IsHex()); } public static bool IsHex(this char c) { c = Char.ToLower(c); if (Char.IsDigit(c) || (c >= 'a' && c <= 'f')) return true; else return false; } 
0
Jun 22 '14 at 16:19
source share

Easy solution without regular expressions:

VB.NET:

 Public Function IsHexString(value As String) As Boolean Dim hx As String = "0123456789ABCDEF" For Each c As Char In value.ToUpper If Not hx.Contains(c) Then Return False Next Return True End Function 

Or in C #

 public bool IsHexString(string value) { string hx = "0123456789ABCDEF"; foreach (char c in value.ToUpper()) { if (!hx.Contains(c)) return false; } return true; } 
0
Jun 18 '15 at 16:57
source share

I am using this method:

 public static bool IsHex(this char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } 
0
Jul 16 '15 at 13:31 on
source share

And this is like a C # extension method ...

 public static class StringExtensions { public static bool IsHexString(this string str) { foreach (var c in str) { var isHex = ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); if (!isHex) { return false; } } return true; } //bonus, verify whether a string can be parsed as byte[] public static bool IsParseableToByteArray(this string str) { return IsHexString(str) && str.Length % 2 == 0; } } 

Use it like that ...

 if("08c9b54d1099e73d121c4200168f252e6e75d215969d253e074a9457d0401cc6".IsHexString()) { //returns true... } 
0
Apr 19 '17 at 10:48 on
source share

I made this solution to solve this problem. Make sure that it doesn't matter before you run the query string.

 for (int i = 0; i < Request.Length; i += 2) if (!byte.TryParse(string.Join("", Request.Skip(i).Take(2)), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)) return false; 
0
May 08 '17 at 10:09 a.m. a.m.
source share
 public static bool HexInCardUID(string test) { if (test.Trim().Length != 14) return false; for (int i = 0; i < test.Length; i++) if (!Uri.IsHexDigit(Convert.ToChar(test.Substring(i, 1)))) return false; return true; }**strong text** 
0
Nov 30 '17 at 7:39 on
source share

Now only

 if (IsHex(text)) { return true; } else { return false; } 
-four
Jun 21 '12 at 17:07
source share



All Articles