r64-bit

Converting hex string to a 64-bit integer/timestamp using R


I need to read 8 bytes in from a binary file and convert it to a timestamp. Getting the data into a character array is not hard. I end up with

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

The data format is endian="little" so if I reverse this array I can get a string which represents the number in hex

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

which yields "08d811e643847711"

Using the bit64 package, I would like to be able to use this

x <- as.integer64(0x8d811e643847711)

but I cannot figure out how to get the string above to be used as an argument to as.integer64. Ie, this generates an error (well, an NA. Not the number ...):

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

Can anyone point me to a solution? TIA, mconsidine


Solution

  • If your hexadecimal number is positive (uppermost bit not set):

    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
    

    Sure you can write this in a more elegant way. But I wanted the code to be obvious.