Binary String to Integer

前端 未结 2 1203
误落风尘
误落风尘 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 19:49

    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

提交回复
热议问题