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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With