Binary String to Integer

前端 未结 2 1192
误落风尘
误落风尘 2020-12-08 19:20

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

At first I naivly used this simple line:

Convert.ToInt32(\"11011\         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 20:09

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

提交回复
热议问题