14

Is there a function which converts a hex string to text in R?

For example:

I've the hex string 1271763355662E324375203137 which should be converted to qv3Uf.2Cu 17.

Does someone know a good solution in R?

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
freiste1
  • 143
  • 1
  • 1
  • 4

3 Answers3

24

Here's one way:

s <- '1271763355662E324375203137'
h <- sapply(seq(1, nchar(s), by=2), function(x) substr(s, x, x+1))
rawToChar(as.raw(strtoi(h, 16L)))

## [1] "\022qv3Uf.2Cu 17"

And if you want, you can sub out non-printable characters as follows:

gsub('[^[:print:]]+', '', rawToChar(as.raw(strtoi(h, 16L))))

## [1] "qv3Uf.2Cu 17"
jbaums
  • 27,115
  • 5
  • 79
  • 119
2

Just to add to @jbaums answer or to simplify it

library(wkb)

hex_string <- '231458716E234987'

hex_raw <- wkb::hex2raw(hex_string)

text <- rawToChar(as.raw(strtoi(hex_raw, 16L)))
iamigham
  • 117
  • 1
  • 4
1

An alternative way that separates the two parts involved:

  1. Turn the initial string into a vector of bytes (with values as hexadecimals)
  2. Convert those raw bytes into characters (excluding any not printable)

Part 1:

s <- '1271763355662E324375203137'
sc <- unlist(strsplit(s, ""))
i1 <- (1:nchar(s)) %% 2 == 1
# vector of bytes (as character)
s_pairs1 <- paste0(sc[i1], sc[!i1])
# make explicit it is a series of hexadecimals bytes
s_pairs2 <- paste0("0x", s_pairs1)
head(s_pairs2)
#> [1] "0x12" "0x71" "0x76" "0x33" "0x55" "0x66"

Part 2:

s_raw1 <- as.raw(s_pairs2) 
# filter non printable values (ascii < 32 = 0x20)
s_raw2 <- s_raw1[s_raw1 >= as.raw("0x20")]
rawToChar(s_raw2)
#> [1] "qv3Uf.2Cu 17"

We could also use as.hexmode() function to turn s_pairs1 into a vector of hexadecimals

s_pairs2 <-  as.hexmode(s_pairs1)
head(s_pairs2)
#> [1] "12" "71" "76" "33" "55" "66"

Created on 2023-01-03 by the reprex package (v2.0.1)

josep maria porrĂ 
  • 1,198
  • 10
  • 18