二进制字符串到整数 [英] Binary String to Integer

查看:126
本文介绍了二进制字符串到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制字符串,由用户,我需要转换为整数输入。

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

起初我naivly用这句简单的话:

At first I naivly 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也许吧。

感谢

推荐答案

您可以使用正则表达式来检查,这是^ [01] + $(或好,^ [01] {1,32} $)和然后的使用转换

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

这篇关于二进制字符串到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆