C# 二进制字符串转整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1271562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:30:03  来源:igfitidea点击:

Binary String to Integer

c#stringbinaryinteger

提问by eric

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

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....but that's just too ugly.
  • something like 'Int32.TryParse' maybe.
  • try..catch.. 但这太丑了。
  • 也许像'Int32.TryParse'这样的东西。

Thanks

谢谢

采纳答案by Marc Gravell

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

您可以使用 aRegex来检查它是否是“^[01]+$”(或者更好,“^[01]{1,32}$”),然后使用Convert?

of course, exceptions are unlikelyto 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);
    }
}

回答by eric

Thanks for the great and incredibly fast answer!

感谢您提供出色且令人难以置信的快速答复!

Unfortunately, my requirements changed. Now the user can pretty much enter any format. Binary, Decimal, Hex. So I decided try - catch just provides the simplest and cleanest solution.

不幸的是,我的要求发生了变化。现在用户几乎可以输入任何格式。二进制、十进制、十六进制。所以我决定尝试 - catch 只是提供最简单和最干净的解决方案。

So just for good measure I am posting the code I am using now. I think it is pretty clear and even somewhat elegant, or so I think^^.

所以只是为了更好的衡量,我发布了我现在正在使用的代码。我认为它很清楚,甚至有点优雅,或者我认为^^。

switch (format)
{
    case VariableFormat.Binary:
        try
        {
            result = Convert.ToInt64(value, 2)
        }
        catch
        {
            // error handling
        }
        break;
    case VariableFormat.Decimal:
        try
        {
            result = Convert.ToInt64(value, 10)
        }
        catch
        {
            // error handling
        }
        break;
    case VariableFormat.Hexadecimal:
        try
        {
            result = Convert.ToInt64(value, 16)
        }
        catch
        {
            // error handling
        }
        break;
}

So thanks for encouraging me to use try - catch, I think it really improved the readibility of my code.

所以感谢鼓励我使用 try - catch,我认为它确实提高了我代码的可读性。

Thanks

谢谢