How to convert `raw` to an integer vector in R?

I need to pass a raw Java backlink through a JRI, but it does not support raws, but only various other vector types (such as integers). How to convert raw (byte vector) to integer vector?

I tried passing the data back as a row vector, but this breaks because the JRI decodes the string incorrectly (for example, "\ x89" is discarded as "").

It would be nice if it were more efficient (unboxed). as.integer does not work - it does not return the value of the bytes of characters in the array, not to mention that rawToChar produces "" for nuls.

+4
source share
3 answers

Taking this step further, you can read Bin directly from the raw vector. Thus, we can:

 > raw [1] 2b 97 53 eb 86 b9 4a c6 6c ca 40 80 06 94 bc 08 3a fb bc f4 > readBin(raw, what='integer', n=length(raw)/4) [1] -346843349 -968181370 -2143237524 146576390 -188941510 
+3
source

See the documentation for rawToChar :

rawToChar converts raw bytes to either a single character string or a character vector of single bytes (with "" for 0).

Of course, once you manage to get it before character , you can easily convert it to an integer using the as.integer method, but be careful .

+2
source

This question is quite old, but for those who (like me) came across this while looking for an answer: as.integer (raw.vec) works well.

 f <- file("/tmp/a.out", "rb") seek(f, 0, "end") f.size <- seek(f, NA, "start") seek(f, 0, "start") raw.vec <- readBin(f, 'raw', f.size, 1, signed=FALSE) close(f) bytes <- as.integer(raw.vec) 
+2
source

All Articles