DateTime <- as.raw(c(0x11, 0x77, 0x84, 0x43, 0xe6, 0x11, 0xd8, 0x08))
数据格式是endian =“little”,所以如果我反转这个数组,我可以得到一个代表十六进制数字的字符串
paste(rev(DateTime),collapse="")
产生“08d811e643847711”使用bit64包,我希望能够使用这个
x <- as.integer64(0x8d811e643847711)
但我不知道如何将上面的字符串用作 as.integer64 的参数。 即,这会产生一个错误(嗯,一个 NA。不是数字......):
x <- as.integer64(paste(rev(DateTime),collapse=""))
有人可以给我指出解决方案吗?
TIA,
麦康定
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)))
hex_to_int64 <- function(hex) {
# remove eventual 0x prefix
hex <- gsub("^0x", "", hex)
# helper function to convert hex to list of bytes
to_bytes <- function(x) {
if (length(x) > 1) return(lapply(x, to_bytes))
y <- strsplit(x, "")[[1]]
sapply(seq(1, length(y), by = 2), function(i) {
as.raw(paste0("0x", paste(y[i:(i + 1)], collapse = "")))
})
}
bytes <- to_bytes(hex)
# unfortunately the conversion to character is needed... otherwise a numeric is returned
sapply(bytes, function(x) {
v <- bit64::as.integer64(0)
for (b in x) v <- 256 * v + as.integer(b)
as.character(v)
}) |> bit64::as.integer64()
}
res <- hex_to_int64(c("ffffffff", "88888888", "00000000"))
res
#> integer64
#> [1] 4294967295 2290649224 0