Skip to content

Instantly share code, notes, and snippets.

@olegcherr
Created May 13, 2020 20:07
Show Gist options
  • Select an option

  • Save olegcherr/fe2e49368ea544b2c61ac66b034e3e0d to your computer and use it in GitHub Desktop.

Select an option

Save olegcherr/fe2e49368ea544b2c61ac66b034e3e0d to your computer and use it in GitHub Desktop.
Base62 encoding/decoding
import java.math.BigInteger
/**
* Base62 encoder/decoder.
*/
object Base62 {
private val BASE = BigInteger.valueOf(62)
private val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
/**
* Encodes a number using Base62 encoding.
*
* @param number a positive integer
* @return a Base62 string
* @throws IllegalArgumentException if `number` is a negative integer
*/
fun encode(number: BigInteger): String {
require(number >= BigInteger.ZERO)
val result = StringBuilder()
var quotient = number
while (quotient > BigInteger.ZERO) {
val divmod = quotient.divideAndRemainder(BASE)
quotient = divmod[0]
val remainder = divmod[1].intValueExact()
result.append(DIGITS[remainder])
}
return when (result.isEmpty()) {
true -> DIGITS.take(1)
else -> result.reverse().toString()
}
}
fun encode(number: Long) = encode(BigInteger.valueOf(number))
/**
* Decodes a string using Base62 encoding.
*
* @param string a Base62 string
* @return a positive integer
* @throws IllegalArgumentException if `string` is empty
*/
fun decode(string: String): BigInteger {
require(string.isNotEmpty())
var result = BigInteger.ZERO
string.forEachIndexed { index, c ->
val digit = DIGITS.indexOf(c)
result = result.add(
BigInteger
.valueOf(digit.toLong())
.multiply(BASE.pow(index))
)
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment