Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a binary string, entered by the user, which I need to convert to an integer.

At first, I naively used this simple line:

Convert.ToInt32("11011",2);

Unfortunately, this throws an exception if the user enters the integer directly.

Convert.ToInt32("123",2); // throws Exception

How can I make sure that the string entered by the user actually is a binary string?

  • try..catch
  • Int32.TryParse

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use a Regex to check that it is "^[01]+$" (or better, "^[01]{1,32}$"), and then use Convert?

of course, exceptions are unlikely to be a huge problem anyway! Inelegant? maybe. But they work.

Example (formatted for vertical space):

static readonly Regex binary = new Regex("^[01]{1,32}$", RegexOptions.Compiled);
static void Main() {
    Test("");
    Test("01101");
    Test("123");
    Test("0110101101010110101010101010001010100011010100101010");
}
static void Test(string s) {
    if (binary.IsMatch(s)) {
        Console.WriteLine(Convert.ToInt32(s, 2));
    } else {
        Console.WriteLine("invalid: " + s);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...