5

What's a quick way to encode either integer values or numeric whole number values in R to a character vector in base 62 encoding, i.e. a string that only contains [a-zA-Z0-9]? Would translating the answer to this question be sufficient? converting a number base 10 to base 62 (a-zA-Z0-9)

Edited

Here's my solution:

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
}

Is that missing anything?

Community
  • 1
  • 1
Jeff
  • 1,426
  • 8
  • 19

3 Answers3

3

Here's a solution that does base 36 using [0-9A-Z] that could easily be adapted for base 62 using [a-zA-Z0-9]. And yes, it's basically just a translation of the solution to the other question you linked to.

https://github.com/graywh/r-gmisc/blob/master/R/baseConvert.R

graywh
  • 9,640
  • 2
  • 29
  • 27
1

Here's a variant of the above code that allows you to convert a vector of numbers to base 16. It's not particularly elegant, as it isn't vectorized, but it gets the job done.

toBase <- function(num, base=16) {
bv <- c(0:9,letters,LETTERS)
r <- list()
q <- list()
res <- list()
for(i in 1:length(num)){
    r[i] <- num[i] %% base
    res[i] <- bv[r[[i]]+1]
    q[i] <- floor(num[i]/base)
    while (q[[i]] > 0L) {
        r[i] <- q[[i]] %% base
        q[i]  <- floor(q[[i]]/base)
        res[i] <- paste(bv[r[[i]]+1],res[[i]],sep='')
    }
}
return(do.call('c', res))
} 
Michael J.
  • 11
  • 1
0

To make this more standard, you should implement it in a similar way to the conversion to hexadecimal. (see here for naming.)

as.exindadeomode <- function(x)
{
  #Give x a class of "exindadeomode"
  #Contents as per as.hexmode
}

format.exindadeomode <- function (x, width = NULL, upper.case = FALSE, ...)
{
  #Return appropriate characters
  #Contents as per format.hexmode
}

To convert back to integer, just strip the class, using as.integer.

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360