How to check C # if input string is binary / hexadecimal. number?

how can I check C # if the input line from the input field is a valid binary (or hexadecimal) number?

+4
source share
3 answers
using System.Globalization; bool valid = int.TryParse(inputString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result); 

works for hexadecimal numbers without a prefix. If you do not know what type of number to expect, you can use

 bool isHex = inputString.Length > 2 && inputString.Substring(0, 2).ToLowerInvariant() == "0x" && int.TryParse(inputString.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result); 

check and parse the string at the same time. For binary, I use

 Regex.IsMatch(inputString, "^[01]+$"); 

You should use inputString = inputString.Trim() to make the application more tolerant of "non-standard input."

+6
source

You can use the following code:

 int dummy; bool isHex = int.TryParse(str, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out dummy); 

There are no built-in functions for the binary, but you can use something like the following:

 static bool isbin(string s) { foreach (var c in s) if (c != '0' && c != '1') return false; return true; } 
+3
source

Try

 Regex.IsMatch("0x6868FC", "\b0x[a-fA-F0-9]+\b"); 

If you expect the user to enter a hexadecimal number starting with 0x.

0
source

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


All Articles