【问题标题】:Convert an integer to base36将整数转换为 base36
【发布时间】:2016-03-16 12:57:43
【问题描述】:

strtoi(x,base=36) 会将 base36 编码的字符串转换为整数:

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

是否有反转此操作的函数,即,给定一个正整数会产生 base36 等效值?本质上,我正在寻找一个 itostr() 函数,这样

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

(我不需要除 36 之外的任何基数,但有一个 base 参数会很好。)

【问题讨论】:

标签: r base36


【解决方案1】:

我相信如果你安装了BBmisc这个包,它就有 itostr 功能可用。

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

【讨论】:

    【解决方案2】:

    我不知道任何实现,但算法并不难。这是一个适用于 32 位有符号整数的方法。

    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=""))
    }
    

    如果您需要支持更大的整数,可以使用bit64Rmpfr 包。

    【讨论】:

    • 不错。我有点吃惊它在intToBase36(1679615) 上中断了,但话又说回来,当然is.integer(1679615)FALSE,使用intToBase36(1679615L) 进行一点强制就可以了。
    【解决方案3】:

    一个快速的 Rcpp hack of this 也会让你得到它:

    library(inline)
    
    cxxfunction(signature(x="numeric"), body='
    unsigned int val = as<unsigned int>(x);
    static char const base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string result;
    result.reserve(14);
    do {
      result = base36[val % 36] + result;
    } while (val /= 36);
    return wrap(result);
    ', plugin="Rcpp") -> base36enc
    
    base36enc(36)
    ## [1] "10"
    
    base36enc(72)
    ## [1] "20"
    
    base36enc(73)
    ## [1] "21"
    

    不过,它肯定需要更多代码用于生产用途。

    另一个答案中引用的BBmisc 包也是C-backed,因此它可能是一个不错的高性能选择。

    【讨论】:

    • #ty 约书亚。我不知道这是怎么发生的(我应该抓住它)
    • 这看起来很有趣,但老实说,作为一个非 Rcpp 用户,这对我来说有点吓人。 (我假设规范的反驳是我 应该 成为 Rcpp 用户。我恳求没有时间。)另外,我收到可能与我的德语默认语言环境有关的神秘错误:“include/Rcpp/ Date.h:103:错误:字段“m_tm”的类型不完整。
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多