'convert hexadecimal string to bytes in R
I have a hex string: '8316cf38737a58ad5fa4a8d5dd07fc7cab068f3ee05a165a5b1f17edf191be88' and I need to convert it to bytes; in R. In python the function binascii.unhexlify accomplishes this and returns b'\x83\x16\xcf8szX\xad_\xa4\xa8\xd5\xdd\x07\xfc|\xab\x06\x8f>\xe0Z\x16Z[\x1f\x17\xed\xf1\x91\xbe\x88'. I cannot locate a function in R that returns the same string. I have tried base64Encode in Rcurl, charToRaw in base and many others to no avail.
Solution 1:[1]
You need to split the string into hex-encode bytes, then turn those strings into numeric values and then tell R that those values are a raw vector. You can do
val <- "8316cf38737a58ad5fa4a8d5dd07fc7cab068f3ee05a165a5b1f17edf191be88"
hex_to_raw <- function(x) {
chars <- strsplit(x, "")[[1]]
as.raw(strtoi(paste0(chars[c(TRUE, FALSE)], chars[c(FALSE, TRUE)]), base=16L))
}
hex_to_raw(val)
# [1] 83 16 cf 38 73 7a 58 ad 5f a4 a8 d5 dd 07 fc 7c ab 06 8f 3e e0
# [22] 5a 16 5a 5b 1f 17 ed f1 91 be 88
You could also skip the paste0() step with
hex_to_raw <- function(x) {
digits <- strtoi(strsplit(x, "")[[1]], base=16L)
as.raw(bitwShiftL(digits[c(TRUE, FALSE)],4) + digits[c(FALSE, TRUE)])
}
Here we just convert each digit from a hex value to a number and then combine them in a pair-wise manner shifting the first member of each pair up by 4 bits and then combining with the lower bits.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
