使用R将十六进制字符串转换为64位整数/时间戳



我需要从二进制文件中读取8个字节,并将其转换为时间戳。将数据放入字符数组并不困难。我最终使用

DateTime <- as.raw(c(0x11, 0x77, 0x84, 0x43, 0xe6, 0x11, 0xd8, 0x08))

数据格式是endian="0";"小";所以如果我反转这个数组,我可以得到一个字符串,它表示十六进制中的数字

paste(rev(DateTime),collapse="")

其产生";08d811e643847711";

使用bit64包,我希望能够使用这个

x <- as.integer64(0x8d811e643847711)

但我不知道如何将上面的字符串用作as.integer64的参数。也就是说,这会产生一个错误(嗯,一个NA。而不是数字…(:

x <- as.integer64(paste(rev(DateTime),collapse=""))

有人能给我指一个解决方案吗?TIA,mconsidine

如果十六进制数为正(最高位未设置(:

require(bit64)
DateTime <- as.raw(c(0x11, 0x77, 0x84, 0x43, 0xe6, 0x11, 0xd8, 0x08))
x <- as.integer64('0')
x <- 256 * x + as.integer(DateTime[1])
x <- 256 * x + as.integer(DateTime[2])
x <- 256 * x + as.integer(DateTime[3])
x <- 256 * x + as.integer(DateTime[4])
x <- 256 * x + as.integer(DateTime[5])
x <- 256 * x + as.integer(DateTime[6])
x <- 256 * x + as.integer(DateTime[7])
x <- 256 * x + as.integer(DateTime[8])
x

当然你可以用更优雅的方式写这篇文章。但我希望代码是显而易见的。

好的,这对我来说是可行的。非常感谢。以下是我最终得到的:

alongint <- function(hexarray){
datain <- as.integer(hexarray)
x <- datain[1]+datain[2]*256+datain[3]*256^2+datain[4]*256^3+
datain[5]*256^4+datain[6]*256^5+datain[7]*256^6+datain[8]*256^7
return(x)  
}
DateTime <- readBin(SERfile,"raw",size=1,8,endian="little")
x <- alongint(DateTime)

矢量化的第一枪(感谢这个想法(:

xtoy <- function(a,b){
return(a*256^b)
}
vxtoy <- Vectorize(xtoy,c("a","b"))
sum(vxtoy(as.integer(DateTime),c(0,1,2,3,4,5,6,7)))

最新更新