Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode a string in hexadecimal representation

Tags:

string

r

In R, what is an efficient way to convert a string encoded in hexadecimal, such as "40414243" to its equivalent characters e.g. "@ABC"?

For instance, the equivalent of this code:

library(stringr)

FromHexString <- function (hex.string) {
  result <- ""
  length <- str_length(hex.string)
  for (i in seq(1, length, by=2)) {
    hex.value <- str_sub(hex.string, i, i + 1)
    char.code <- strtoi(hex.value, 16)
    char <- rawToChar(as.raw(char.code))
    result <- paste(result, char, sep="")
    char
  }
  result
}

Which produces:

> FromHexString("40414243")
[1] "@ABC"

While the above code works, it's not efficient at all, using a lot of string concatenations.

So the question is how to write an idiomatic, efficient R function that does this operation.

Edit: My sample works only for ASCII encoding, not for UTF-8 encoded byte arrays.

like image 731
Fernando Correia Avatar asked Jan 18 '26 15:01

Fernando Correia


1 Answers

Test if that is more efficient (for longer strings):

string <- "40414243"

intToUtf8(
  strtoi(
    do.call(
      paste0, 
      as.data.frame(
        matrix(
          strsplit(string, split = "")[[1]], 
          ncol=2, 
          byrow=TRUE), 
        stringsAsFactors=FALSE)), 
    base=16L)
)
#[1] "@ABC"

Otherwise you could look for a C/C++ implementation.

like image 120
Roland Avatar answered Jan 20 '26 06:01

Roland