Skip to content

Instantly share code, notes, and snippets.

@dayanruben
Last active June 29, 2020 00:39
Show Gist options
  • Select an option

  • Save dayanruben/178672edba4d8648a13ca3ac60a6a386 to your computer and use it in GitHub Desktop.

Select an option

Save dayanruben/178672edba4d8648a13ca3ac60a6a386 to your computer and use it in GitHub Desktop.
Base62 encoding/decoding
class Base62 {
val order = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
val base = order.length
fun encode(number: Int): String {
var num = number
var res = ""
while (num > 0) {
res = "${order[num % base]}$res"
num /= base
}
return res
}
fun decode(code: String): Int {
val reversedCode = code.reversed()
return code.indices.sumBy { i -> Math.pow(base.toDouble(), i.toDouble()).toInt() * order.indexOf(reversedCode[i])}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment