Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to base36

Tags:

r

base36

strtoi(x,base=36) will convert a base36-encoded string to an integer:

strtoi("zzzz",base=36)
[1] 1679615

Is there a function that inverts this operation, i.e., given a positive integer yields the base36 equivalent? Essentially, I'm looking for an itostr() function such that

itostr(1679615,base=36)
[1] "zzzz"

(I don't need any base other than 36, but a base argument would be nice to have.)

like image 666
Stephan Kolassa Avatar asked Mar 16 '16 12:03

Stephan Kolassa


People also ask

What is Base36 encoding?

Base36 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-36 representation. The choice of 36 is convenient in that the digits can be represented using the Arabic numerals 0–9 and the Latin letters A–Z (the ISO basic Latin alphabet).

How do you turn an integer into a base?

Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.

How do you convert to base 26?

Convert the decimal 12345 to base 26. Method 1: Find the highest power of 26 that is less than 12345. 262=676 26 2 = 676 and 263=17576 26 3 = 17576 so 262 is the highest power of 26 that is less than 12345. Next, divide 12345 by 676=262 676 = 26 2 to find a quotient and remainder.


2 Answers

I believe if you install the package BBmisc, it has the itostr function is available.

library(BBmisc)
itostr(1679615,base=36)
[1] "zzzz"
like image 60
justin1.618 Avatar answered Sep 30 '22 10:09

justin1.618


I don't know of any implementations, but the algorithm isn't that difficult. Here's one that works on 32-bit signed integers.

intToBase36 <- function(int) {
  stopifnot(is.integer(int) || int < 0)

  base36 <- c(as.character(0:9),LETTERS)
  result <- character(6)
  i <- 1L
  while (int > 0) {
    result[i] <- base36[int %% 36L + 1L]
    i <- i + 1L
    int <- int %/% 36L
  }
  return(paste(result, sep="", collapse=""))
}

You could use the bit64 and Rmpfr packages if you need to support larger integers.

like image 35
Joshua Ulrich Avatar answered Sep 30 '22 09:09

Joshua Ulrich