Last active
May 12, 2016 10:41
-
-
Save sketchytech/b3e746aa90e0745d95c491280545f99f to your computer and use it in GitHub Desktop.
Swift: Conversion to different number bases (radix)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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