I am struggling with importing data from a binary file into R. Among others, the data file contains a 64 bit unsigned integer value (little Endian) which I need to read out.
The value represents the number of seconds since 12:00 am, January 1, 1900 and is to be converted to a date and time value (e.g. YYMMDDhhmmss).
As a beginner I have read about some packages (bit64, int64) but it seems they don't support unsigned integers or aren't maintained any longer.
Can someone please help me?
Use readBin to read the file into a raw vector, then convert manually.
# sample data
zz <- file("myBinaryFile", "wb")
writeBin(32L, zz, size=8L, endian="little")
close(zz)
# now read the data
zz <- file("myBinaryFile", "rb")
# n can be a mild over-estimate
rawvec <- readBin(zz, raw(), n=10, endian="little")
close(zz)
# convert the value to a number
nsec <- sum(2^.subset(0:63, as.logical(rawToBits(rawvec))))
# convert the number to POSIXct
as.POSIXct(nsec, tz="UTC", origin=as.POSIXct("1900-01-01", tz="UTC"))
Note that nsec will be a numeric/double value, since R's integers are 32-bit and signed. That shouldn't be a problem unless you have some datetimes that are way out in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With