Reputation: 16416
I need to pass a raw back to Java via JRI, but it doesn't support raws, only various other vector types (such as integers). How do I convert a raw (vector of bytes) into a vector of integers?
I tried passing the data back as a vector of strings, but that breaks because JRI doesn't decode the string properly (eg '\x89' gets discarded as "").
Would also be nice if it were more efficient (unboxed). as.integer
does not work - it doesn't return the byte values of the characters in the array, not to mention the fact that rawToChar produces "" for nuls.
Upvotes: 5
Views: 7476
Reputation: 5202
Taking this a stage further, you can readBin directly from a raw vector. So 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
Upvotes: 6
Reputation: 346
This question is pretty old, but for those who (like myself) came across this while searching 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)
Upvotes: 3
Reputation: 36080
See documentation for rawToChar
:
rawToChar converts raw bytes either to a single character string or a character vector of single bytes (with "" for 0).
Of course, once you manage to get it to character
, you can easily convert it to integer via as.integer
method, but be cautious.
Upvotes: 2