用NUL值解码R中的十六进制

问题描述 投票:0回答:1

很明显,R不允许使用空字符:

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

我正在尝试解码十六进制字符串并将结果写入文件。 NUL对我而言至关重要。现在,我已经写了这么多:

# 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")`

我如何更改as.raw(0)部分,在文件中我会看到NUL值,而不是00?在R中甚至可以这样做吗?也许我应该改用其他程序,例如python?

r hex decode
1个回答
0
投票

我不明白您为什么要将这些值转换为字符。为什么不将它们保留为数值,然后使用writeBin将其写出? R为此提供了良好的支持。例如,

# 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 <- as.hexmode(hex)  # Converts to integer vector that prints in hex
writeBin(unclass(x), "test1", size=1)
© www.soinside.com 2019 - 2024. All rights reserved.