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,
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