How to convert a binary to decimal in Swift?

后端 未结 4 1219
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 05:12

I am looking for a simple way to convert a binary number in decimal in Swift. For example, \"10\" in binary becomes \"2\" in decimal.

Thanks,

4条回答
  •  醉酒成梦
    2020-12-05 05:33

    There may be a built-in to do this, but writing the code yourself isn't hard:

    func parseBinary(binary: String) -> Int? {
        var result: Int = 0
    
        for digit in binary {
            switch(digit) {
                case "0": result = result * 2
                case "1": result = result * 2 + 1
                default: return nil
            }
        }
        return result
    }
    

    The function returns an (optional) Int. If you want to get a string instead, you can do the following:

    String(parseBinary("10101")!)
    -> "21"
    

    Note the forced unwrapping (!) If the string you provide contains anything other than 0's or 1's, the function returns nil and this expression will blow up.

    Or, taking a cue from Leonardo, you can build this as an extension to string:

    extension String {
        func asBinary() -> Int? {
            var result: Int = 0
    
            for digit in self {
                switch(digit) {
                    case "0": result = result * 2
                    case "1": result = result * 2 + 1
                    default: return nil
                }
            }
            return result
        }
    }
    
    "101".asBinary()!
    -> 5
    

提交回复
热议问题