Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check in c# if a input string is a binary/hexa. number?

Tags:

c#

binary

how can i check in c# if a input string from a input field is a correct binary (or hexa) number?

like image 572
malltteee Avatar asked Dec 29 '22 00:12

malltteee


2 Answers

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".

like image 107
Tamschi Avatar answered Dec 30 '22 13:12

Tamschi


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;
}
like image 35
Vlad Avatar answered Dec 30 '22 14:12

Vlad