how can i check in c# if a input string from a input field is a correct binary (or hexa) number?
using System.Globalization;
bool valid = int.TryParse(inputString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result);
works for hex numbers without prefix. If you don't know wich number type 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);
to check and parse the string at the same time. For binary I'd use
Regex.IsMatch(inputString, "^[01]+$");
You should use inputString = inputString.Trim()
to make the application more tolerant regarding "non-standard input".
You can use the following code:
int dummy;
bool isHex = int.TryParse(str,
NumberStyles.HexNumber,
CultureInfo.InvariantCulture,
out dummy);
For the binary, there are no built-in functions, but you can use something like following:
static bool isbin(string s)
{
foreach (var c in s)
if (c != '0' && c != '1')
return false;
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With