Reputation: 3147
I need to read a binary file which encodes longs. I give just one of the longs as an example.
# don't know a simpler way to create the raw vector
z <- writeBin(c(8L, 208L, 59L, 233L, 106L, 151L, 126L, 73L), raw())
dim(z) <- c(4,8)
z1 <- z[1,]
#[1] 08 d0 3b e9 6a 97 7e 49
The vector z1 is in binary (e.g. http://www.asciitohex.com/):
00001000 11010000 00111011 11101001 01101010 10010111 01111110 01001001
which is in decimal (java.lang.Long.parseLong( v,2)):
635073421160971849
> readBin(z1, what="integer", size=8, n=1 )
[1] -381956088
> readBin(z1, what="integer", size=8, n=1, endian="big")
[1] 1788313161
#etc...
Which is not what I want. How do I do the conversion from the raw vector in R?
Upvotes: 2
Views: 1005
Reputation: 7396
This is hackish and unstraightforward and foolish and all that, but since I also think it's interesting, I couldn't resist trying. And since I tried, I'm going to post it.
Joshua is right in that int64
doesn't support conversion from raw
. However, it just stores each 64-bit integer as two 32-bit integers, so you could convert your raw
to an int64
by splitting it into two and reading each piece as an integer:
> my.long <- int64(1)
> [email protected][[1]] <- c(readBin(z1[1:4], what="integer", endian="big"), readBin(z1[5:8], what="integer", endian="big"))
> my.long
[1] 635073421160971849
Upvotes: 3
Reputation: 176718
Looks like you can do this with the gmp package, if you convert your raw vector into a character format. I used hex in the example below.
#install.packages("gmp")
library(gmp)
as.bigz(paste0("0x",paste0(as.character(z1),collapse="")))
# Big Integer ('bigz') :
# [1] 635073421160971849
Upvotes: 3