Skip to content

Instantly share code, notes, and snippets.

@cathandnya
Last active May 2, 2019 14:18
Show Gist options
  • Save cathandnya/c6200cb51b5a4720b882 to your computer and use it in GitHub Desktop.
Save cathandnya/c6200cb51b5a4720b882 to your computer and use it in GitHub Desktop.
base36 or base58 decoder
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")
}
}
@rogerluan
Copy link

rogerluan commented May 2, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment