To convert a number from base 2 to base 10 in Swift, follow these steps:
Initialize a variable to hold the decimal equivalent of the binary number, starting at 0.
Loop through each digit of the binary number, starting from the rightmost digit.
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).
Add the result of the multiplication to the decimal value.
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.swift293 chars13 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.swift118 chars4 lines
gistlibby LogSnag