LoginSignup
7
7

More than 5 years have passed since last update.

R で n 進数を 10 進数に変換する #rstatsj

Last updated at Posted at 2016-04-20

R で 32進数を 10進数に変換する必要があったので書きました。

R
base2dec <- function(str, base = 32) {
  chars_list <- strsplit(str, split = "")
  sapply(chars_list, function(chars) {
    n <- length(chars)
    digits <- sapply(seq_len(n), function(i) {
      char <- tolower(chars[i])
      tryCatch(as.integer(char), warning = function(e) {
        which(letters == char) + 9
      })
    })
    sum(digits * base^(n-seq_len(n)))
  })
}

こんな感じで使います。

> base2dec("100", base = 10)
[1] 100

> base2dec("ff", base = 16)
[1] 255

> base2dec("11", base = 32)
[1] 33

ちなみに、8進数と 16進数に対しては、as.octmode()as.hexmode() という関数がそれぞれ用意されていて、次のようにして変換できます。

> as.integer(as.octmode("10"))
[1] 8

> as.integer(as.hexmode("ff"))
[1] 255

Enjoy!

追記

ていうか、as.hexmode() の中身を覗いてみると、strtoi() という関数があることに気づきました。

> strtoi("10", base = 8)
[1] 8

> strtoi("ff", base = 16)
[1] 255

> strtoi("11", base = 32)
[1] 33

これでええやん。。orz

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7