Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active May 12, 2016 10:41
Show Gist options
  • Select an option

  • Save sketchytech/b3e746aa90e0745d95c491280545f99f to your computer and use it in GitHub Desktop.

Select an option

Save sketchytech/b3e746aa90e0745d95c491280545f99f to your computer and use it in GitHub Desktop.
Swift: Conversion to different number bases (radix)
extension IntegerType {
public func toBase(b:Int) -> String
{
guard b > 1 && b < 37 else {
fatalError("base out of range")
}
let digits = ["0","1","2","3","4","5","6","7","8","9","A",
"B","C","D","E","F","G","H","I","J","K","L",
"M","N","O","P","Q","R","S","T","U","V","W",
"X","Y","Z"]
var result = ""
if let v = self as? Int {
var value = abs(v)
repeat {
result = digits[value % b] + result
value = value / b
} while (value > 0)
}
return self > 0 ? result : "-" + result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment