rradixbase-conversion

How to convert decimal (base 10) numbers to ternary (base 3)


I was wondering if there is a way to convert decimal numbers to ternary, given that there is a function intToBits for converting to binary.

I actually need to convert a character string like

> S0 <- c("Hello Stac")

to base 3. I thought to first convert it to decimal with

> S01 <- utf8ToInt(S0)
> S01
## [1]  72 101 108 108 111  32  83 116  97  99

then convert the result to base 3. I want to obtain something like this:

> S1
## [1] 2200 10202 11000 11010  11022 1012 10002 11022 10121 10200

Solution

  • For practice, I guess you can try to write your own converter function like below

    f <- function(x, base = 3) {
      q <- c()
      while (x) {
        q <- c(x %% base, q)
        x <- x %/% base
      }
      # as.numeric(paste0(q, collapse = ""))
      sum(q * 10^(rev(seq_along(q) - 1)))
    }
    

    or with recursion

    f <- function(x, base = 3) {
      ifelse(x < base, x, f(x %/% base) * 10 + x %% base)
    }
    

    then you can run

    > sapply(utf8ToInt(S0),f)
     [1]  2200 10202 11000 11000 11010  1012 10002 11022 10121 10200