将R中的整数值或数字整数值编码为基本62编码中的字符向量的快速方法是什么,即只包含[a-zA-Z0-9]的字符串?翻译这个问题的答案是否足够? 将数字基数10转换为基数62(a-zA-Z0-9)
编辑
这是我的解决方案:
toBase <- function(num, base=62) {
bv <- c(seq(0,9),letters,LETTERS)
r <- num %% base
res <- bv[r+1]
q <- floor(num/base)
while (q > 0L) {
r <- q %% base
q <- floor(q/base)
res <- paste(bv[r+1],res,sep='')
}
res
}
to10 <- function(num, base=62) {
bv <- c(seq(0,9),letters,LETTERS)
vb <- list()
for (i in 1:length(bv)) vb[[bv[i]]] <- i
num <- strsplit(num,'')[[1]]
res <- vb[[num[1]]]-1
if (length(num) > 1)
for (i in 2:length(num)) res <- base * res + (vb[[num[i]]]-1)
res
}
Run Code Online (Sandbox Code Playgroud)
这有什么遗漏吗?
这是一个使用 [0-9A-Z] 进行基数 36 的解决方案,可以轻松地使用 [a-zA-Z0-9] 进行基数 62 的解决方案。是的,它基本上只是您链接到的其他问题的解决方案的翻译。
https://github.com/graywh/r-gmisc/blob/master/R/baseConvert.R