malltteee
malltteee

Reputation: 87

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

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

Upvotes: 4

Views: 16982

Answers (3)

Vlad
Vlad

Reputation: 35594

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;
}

Upvotes: 3

Tamschi
Tamschi

Reputation: 1140

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

Upvotes: 7

Aliostad
Aliostad

Reputation: 81660

Try

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

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

Upvotes: 0

Related Questions