convert a number from base 10 to base 8 in swift

To convert a number from base 10 to base 8 in Swift, you can use the built-in String initializer that takes in a radix as a parameter. Here is the algorithm:

  1. Get the decimal number as input.
  2. Convert the decimal number to a string representation in base 8 using the String initializer with a radix of 8.
  3. Return the string representation of the number in base 8.

Here is the code in Swift:

main.swift
func convertToBase8(decimal: Int) -> String {
    return String(decimal, radix: 8)
}
85 chars
4 lines

You can call this function with a decimal input and it will return the corresponding string representation of the number in base 8.

Example usage:

main.swift
let decimalNumber = 23
let base8Number = convertToBase8(decimal: decimalNumber)
print(base8Number) // Output: "27"
115 chars
4 lines

In this example, the decimal number 23 is converted to its base 8 representation, which is the string "27". The function returns this string as the output.

gistlibby LogSnag