简体   繁体   中英

Convert hexadecimal character vector to raw vector in R

I am trying to convert a hexadecimal character vector shown below into a raw vector,

"58" "0a" "00" "00" "00" "02" "00" "03" "02" "00" "00" "02" "03" "00" "00" "00" "03" "13" "00" "00"

I have tried it using this code,

as.raw(hexvec)

But, this gives me the following result,

3a 00 00 00 00 02 00 03 02 00
Warning messages:
1: NAs introduced by coercion 
2: out-of-range values treated as 0 in coercion to raw

What I want is the same vector in Raw type vector(as returned by serialize function). Can anyone help me with this?

I guess it's way to late to awser but it might help somebody else.

hexchar_vector <- c("58", "0a", "00", "00", "00", "02", "00", "03", "02", "00", "00", "02", "03", "00", "00", "00", "03", "13", "00", "00")

integer_vector <- base::strtoi(hexchar_vector, base = 16L) # Convert strings to integers according to the given base using the C function strtol, or choose a suitable base following the C rules.

raw_vector <- base::as.raw(integer_vector) # Creates objects of type "raw" from integers.

This gives, with pipes and without the namespace referal :

library(magrittr)
hexchar_vector <- c("58", "0a", "00", "00", "00", "02", "00", "03", "02", "00", "00", "02", "03", "00", "00", "00", "03", "13", "00", "00")

raw_vector  <- hexchar_vector %>%
  strtoi(16L) %>%
  as.raw()

Have you tried to apply the function charToRaw for each element in the vector?
Try to use this code?

 sapply(hexvec,charToRaw)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM