Binary String to Integer

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


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