Grant Emerson

Binary To Decimal

Binary To Decimal — SwiftMoji Entry #20

Swift offers a generic initializer on Int for converting non-base-10 numerical Strings such as binary, octal, or hexadecimal to the decimal format. The initializer is written as init(_:radix:) where the first parameter is the numerical data encoded in a type conforming to the StringProtocol, and the second, labeled radix, is the base for conversion. The radix must be between 2 and 36. If a character in the input String lies beyond the bounds of the specified radix, the initializer fails and returns nil. In the code example, a binary encoded phone number is converted back to decimal using a radix of 2.

let binaryMessage = "101001011001000101111011110101011"
let 📞🔢 = Int(binaryMessage, radix: 2)!
print(📞🔢) // 5555550123
Tagged with: