convert a number from base 2 to base 10 in swift

To convert a number from base 2 to base 10 in Swift, follow these steps:

  1. Initialize a variable to hold the decimal equivalent of the binary number, starting at 0.

  2. Loop through each digit of the binary number, starting from the rightmost digit.

  3. For each digit, multiply its value (0 or 1) by 2 raised to the power of its position (starting from 0 for the rightmost digit).

  4. Add the result of the multiplication to the decimal value.

  5. After all digits have been processed, the decimal value will be the equivalent in base 10.

Here's the Swift code to implement this algorithm:

main.swift
func binaryToDecimal(binary: String) -> Int {
    var decimal = 0
    var position = 0
    
    for digit in binary.reversed() {
        if let value = Int(String(digit)) {
            decimal += value * Int(pow(2, Double(position)))
        }
        position += 1
    }
    return decimal
}
293 chars
13 lines

To convert a binary number represented as a string, call the binaryToDecimal function with the string as an argument. The function returns the decimal equivalent as an integer.

Example usage:

main.swift
let binaryString = "1011"
let decimalValue = binaryToDecimal(binary: binaryString)
print(decimalValue)  // Output: 11
118 chars
4 lines

gistlibby LogSnag