Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to convert a number to any base in Swift

1 Answer

0 votes
import Foundation

enum BaseConvertError: Error {
    case invalidBase
}

func toBase(_ n: Int, base: Int) throws -> String {
    let digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    guard base >= 2 && base <= 36 else {
        throw BaseConvertError.invalidBase
    }

    if n == 0 {
        return "0"
    }

    var value = n
    var result = ""

    while value > 0 {
        let remainder = value % base
        let index = digits.index(digits.startIndex, offsetBy: remainder)
        result.append(digits[index])
        value /= base
    }

    return String(result.reversed())
}

let number = 25
        let bases = [2, 8, 16, 36]

        for b in bases {
            do {
                let converted = try toBase(number, base: b)
                print("\(number) in base \(b) = \(converted)")
            } catch {
                print("Error converting to base \(b): \(error)")
            }
        }



/*
 The decimal number 25 is represented as P in base-36. 
 Base-36 uses digits 0-9 followed by letters A-Z (where A=10, B=11, ..., P=25, ..., Z=35) 
 to represent values. 
*/


/*
run:

25 in base 2 = 11001
25 in base 8 = 31
25 in base 16 = 19
25 in base 36 = P

*/

 



answered 4 hours ago by avibootz
...