Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a string to see if all characters are hexadecimal values

Tags:

c#

What is the most efficient way in C# 2.0 to check each character in a string and return true if they are 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 } 
like image 361
Guy Avatar asked Oct 21 '08 22:10

Guy


People also ask

How do you know if a string is hexadecimal?

If you want to check if the input is in hexadecimal format, you shouldn't trim it at the beginning. Also, your loop could fail faster if you just return false on the first occurrence of a non-hex character (there's probably some method to check for containment so you could do: if (! hexDigits.

How many characters is a hexadecimal string?

Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.


2 Answers

Something like this:

(I don't know C# so I'm not sure how to loop through the chars of a string.)

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; 

Code for 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; } 
like image 86
Paige Ruten Avatar answered Oct 05 '22 13:10

Paige Ruten


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"); } 
like image 24
Christian C. Salvadó Avatar answered Oct 05 '22 13:10

Christian C. Salvadó