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.)
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).
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.
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.
I believe if you install the package BBmisc, it has the itostr function is available.
library(BBmisc)
itostr(1679615,base=36)
[1] "zzzz"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With