object Test extends App {
def strNumToBaseFromBase(literal: String, tgtBase: Int, curBase: Int = 10): String = {
import scala.math._
val ls1 = (0 until 66).toList
val ls2 = ('0' to '9') :++ ('a' to 'z') :++ ('A' to 'Z') :++ List('+', '-', '*', '/')
val map1To2 = (ls1.take(tgtBase) zip ls2.take(tgtBase)).toMap
val map2To1 = (ls2.take(curBase) zip ls1.take(curBase)).toMap
var numBase10: BigInt = 0
if (curBase == 10) {
numBase10 = BigInt(literal)
} else {
for (c <- literal)
numBase10 = numBase10 * curBase + map2To1(c)
}
if (tgtBase == 10) {
numBase10.toString
} else {
var lsRes = List[Char]()
while (numBase10 > 0) {
lsRes :+= map1To2((numBase10 % tgtBase).toInt)
numBase10 /= tgtBase
}
lsRes.reverse.map(_.toString).reduce(_ + _)
}
}
BigInt(1234567).toString(36)
strNumToBaseFromBase("1234567", 36)
strNumToBaseFromBase("qglj", 10, 36)
extension (literal: String):
def toBaseFromBase(tgtBase: Int, curBase: Int = 10): String =
import scala.math._
val ls1 = (0 until 66).toList
val ls2 = ('0' to '9') :++ ('a' to 'z') :++ ('A' to 'Z') :++ List('+', '-', '*', '/')
val map1To2 = (ls1.take(tgtBase) zip ls2.take(tgtBase)).toMap
val map2To1 = (ls2.take(curBase) zip ls1.take(curBase)).toMap
var numBase10: BigInt = 0
for c <- literal do
numBase10 = numBase10 * curBase + map2To1(c)
var lsRes = List[Char]()
while numBase10 > 0 do
lsRes :+= map1To2((numBase10 % tgtBase).toInt)
numBase10 /= tgtBase
lsRes.reverse.map(_.toString).reduce(_ + _)
val test = "HelloWorld".toBaseFromBase(10, 62)
}