我有一个file其中包含原始/二进制数据和 ascii。 它包含一个时间戳和一个代表速度的无符号 16 位值。 我想用“R”绘制该速度,因此读取该文件。
该文件的定义是:
自午夜以来的毫秒数 - 采用 ascii
+ ':$'
+ BufferStr
+ #13#10
BufferString 然后包含我想要提取的以下信息:
字节 3:序列字(无符号)
字节 4 和 5:速度(无符号)
...
我想生成一个包含 2 列时间和速度的表格
我的方法是将文件作为 csv 读取一次以获取时间戳列。
library(bit)
dataPath="rawdata.txt"
#to create time col read file as csv:
rwch=read.csv(dataPath, sep=":")
然后再次以二进制形式读取文件。 我将文件分成 27 字节的片段,即一行的长度。
#read binary
to.read = file(path, "rb")
rw=readBin(to.read, what="raw", n = 100*27, endian = "big")
rws=split(rw, ceiling(seq_along(rw)/27))
但后来我卡住了。生成的向量不包含原始数据,我无法再次分割它以获取速度。 我尝试了几个函数,例如 hexView 、readRaw 但我无法生成我的列表。
我很高兴收到任何提示
最佳答案
最好在正在处理的连接上使用 readBin(),而不是尝试读取整个文件(除非文件中只有一种 data.type,但这里有混合类型)。这似乎适用于您的示例文件。
N<-28
RC<-27
secs<-numeric(N)
speeds<-numeric(N)
con<-file("/rawdata.txt", "rb")
for(i in seq.int(N)) {
print(i)
secs[i] <- as.numeric(readChar(con,8))
stopifnot(readChar(con,2)==":$") #check
readBin(con,"raw",3) #skip 3 bytes
speeds[i] <- readBin(con, "int",1,2, signed=F)
readBin(con,"raw",10) #skip 10 bytes
stopifnot(readBin(con,"raw",2)==c(13,10)) #check
}
data.frame(secs,speeds)
close(con)
关于使用 R 读取和转换二进制原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23431346/