简体   繁体   中英

Decode hex in R with NUL values

It is obvious that R doesn't alow nul characters:

c("abc\0d")
Error: nul character not allowed (line 1)

I'm trying to decode hex string and write results to a file. NUL values a crucial for me. For now, i have written this much:

# Example of hex string
msg <- '504F03032C0000000803F8'
hex <- sapply(seq(1, nchar(as.character(msg)), by=2), 
              function(x) substr(msg, x, x+1))

# trying to decode hex
x <- NULL
for( i in 1:length(hex)){
  x[i] <- as.character(ifelse(hex[i] == "00", as.raw(0), rawToChar(as.raw(strtoi(hex[i], 16L)))))
}

write(paste0(x, collapse = ""), "test1")`

How could I change as.raw(0) part that in file i would see NUL value, not 00? Is it even possible to do so in R? Maybe I should change to other program, like python?

I don't understand why you want to convert those values to character. Why not keep them as numeric values, and use writeBin to write them out? R has good support for that. For example,

# Example of hex string
msg <- '504F03032C0000000803F8'

# Use solution from https://stackoverflow.com/a/2247574/2554330 to split
hex <- substring(msg, seq(1, nchar(msg), 2), seq(2, nchar(msg), 2))

# trying to decode hex
x <- strtoi(hex, 16)  # Converts to integer vector
writeBin(x, "test1", size=1)

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