Binary String to Integer

六眼飞鱼酱① 提交于 2019-12-17 23:46:35

问题


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.

Thanks


回答1:


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



回答2:


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.

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.

Thanks



来源:https://stackoverflow.com/questions/1271562/binary-string-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!