Last active
May 2, 2019 14:18
-
-
Save cathandnya/c6200cb51b5a4720b882 to your computer and use it in GitHub Desktop.
base36 or base58 decoder
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
import Foundation | |
extension String { | |
func baseUnitValue(letters: String) -> Int? { | |
let base = countElements(letters) | |
func getNum(s: String) -> Int? { | |
if let idx = letters.rangeOfString(s) { | |
return distance(letters.startIndex, idx.startIndex) | |
} else { | |
return nil | |
} | |
} | |
var ret = 0 | |
var m = 1 | |
var i = self.endIndex | |
do { | |
let s = self.substringWithRange(Range<String.Index>(start: advance(i, -1), end: i)) | |
if let num = getNum(s) { | |
ret += num * m | |
} else { | |
return nil | |
} | |
m *= base | |
i = advance(i, -1) | |
} while (distance(self.startIndex, i) > 0) | |
return ret | |
} | |
var base58Value: Int? { | |
return baseUnitValue("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ") | |
} | |
var base36Value: Int? { | |
return baseUnitValue("0123456789abcdefghijklmnopqrstuvwxyz") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For Base 2~36 we now have this built-in in the Swift Standard Library:
Encode: https://developer.apple.com/documentation/swift/string/2997127-init
Decode: https://developer.apple.com/documentation/swift/int/2924481-init
It doens't work for 58, though.