Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A base converter in Swift 3. For instance, BaseConverter.representNumber(number: 3405691582, inBase: 16) is "cafebabe"
import Foundation
public struct BaseConverter
{
static let alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // 62 digits
static func representNumber(n: Int, asciiAlphabet: String) -> String
{
let base = asciiAlphabet.lengthOfBytes(using: String.Encoding.utf8)
if (n < base){
return asciiSubstringOf(string: asciiAlphabet, start: n, end: n + 1)
} else {
// Get the number minus the last digit and do a recursive call.
// Note that division between integer drops the decimals, eg: 769/10 = 76
let newNumber = Int(trunc(Double(n / base)))
let digit1 = representNumber(n: newNumber, asciiAlphabet: asciiAlphabet)
let nModBase = n % base
let digit2 = asciiSubstringOf(string: asciiAlphabet, start: nModBase, end: nModBase + 1)
return "\(digit1)\(digit2)"
}
}
static func representNumber(number: Int, inBase base: Int) -> String
{
let length = alphabet.lengthOfBytes(using: String.Encoding.ascii)
assert(length >= Int(base), "Not enough characters. Use base \(length) or lower.")
let subAlphabet = asciiSubstringOf(string: alphabet, start: 0, end: base)
let representation = representNumber(n: number, asciiAlphabet: subAlphabet)
print("number \(number) represented in base \(base) using alphabet \(subAlphabet) is \(representation)")
return representation
}
static func asciiSubstringOf(string: String, start: Int, end: Int) -> String
{
assert(start <= end)
let length = string.lengthOfBytes(using: String.Encoding.ascii)
if end > length {
return ""
}
let lo = string.index(string.startIndex, offsetBy: start)
let hi = string.index(string.startIndex, offsetBy: end)
let substring = string.substring(with: lo..<hi)
return substring
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.