ASCII Character to Decimal Value in R

946 Views Asked by At

Given a word I need to find the decimal values of each letter in that word and store it in an array. I used strtoi function to achieve this. But later found out below two functions which are supposed to give same output are giving different result. Can anyone explain why?
1st attempt

> strtoi("d",16L)
[1] 13

2nd attempt

> strtoi(charToRaw("d"),16L)
[1] 100

And what does 16L in the base of srtoi mean? I am fairly new to Dec, Hex, Oct representation of ASCII characters. So please share some information about it.

1

There are 1 best solutions below

0
On

For illustration purposes only:

library(purrr)
library(tibble)

input_str <- "Alphabet."

charToRaw(input_str) %>%
  map_df(~data_frame(letter=rawToChar(.),
                     hex_value=toString(.),
                     decimal_value=as.numeric(.)))
## # A tibble: 9 × 3
##   letter hex_value decimal_value
##    <chr>     <chr>         <dbl>
## 1      A        41            65
## 2      l        6c           108
## 3      p        70           112
## 4      h        68           104
## 5      a        61            97
## 6      b        62            98
## 7      e        65           101
## 8      t        74           116
## 9      .        2e            46

Since what you need to do can be done all in base R:

as.numeric(charToRaw(input_str))
## [1]  65 108 112 104  97  98 101 116  46

You can also do as.integer() vs as.numeric() if you just need/want integers.