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,
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,
Update for Swift 2: All integer types have an
public init?(_ text: String, radix: Int = default)
method now, which converts a string to an integer according to a given base:
let binary = "11001"
if let number = Int(binary, radix: 2) {
print(number) // Output: 25
}
(Previous answer:) You can simply use the BSD library function strtoul()
, which converts a string to
a number according to a given base:
let binary = "11001"
let number = strtoul(binary, nil, 2)
println(number) // Output: 25
Update: Xcode 7.2 • Swift 2.1.1
You can implement Martin R's Answer making an extension using C++ function called strtoul as follow:
extension String {
var hexaToInt : Int { return Int(strtoul(self, nil, 16)) }
var hexaToDouble : Double { return Double(strtoul(self, nil, 16)) }
var hexaToBinary : String { return String(hexaToInt, radix: 2) }
var decimalToHexa : String { return String(Int(self) ?? 0, radix: 16)}
var decimalToBinary: String { return String(Int(self) ?? 0, radix: 2) }
var binaryToInt : Int { return Int(strtoul(self, nil, 2)) }
var binaryToDouble : Double { return Double(strtoul(self, nil, 2)) }
var binaryToHexa : String { return String(binaryToInt, radix: 16) }
}
extension Int {
var binaryString: String { return String(self, radix: 2) }
var hexaString : String { return String(self, radix: 16) }
var doubleValue : Double { return Double(self) }
}
"ff".hexaToInt // "255"
"ff".hexaToDouble // "255.0"
"ff".hexaToBinary // "11111111"
"255".decimalToHexa // "ff"
"255".decimalToBinary // "11111111"
"11111111".binaryToInt // "255"
"11111111".binaryToDouble // "255.0"
"11111111".binaryToHexa // "ff"
255.binaryString // "11111111"
255.hexaString // "ff"
255.doubleValue // 255.0
binary is built-in to swift using 0b prefix
println( 0b11001 ) // Output: 25
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
© 2022 - 2024 — McMap. All rights reserved.