开发者

How do I convert a `raw` into a vector of integers in R?

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 m开发者_Go百科ore 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.


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  


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜