5

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.

Yang
  • 16,037
  • 15
  • 100
  • 142

3 Answers3

6

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  
dsz
  • 4,542
  • 39
  • 35
3

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)
mkfs
  • 346
  • 1
  • 6
2

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.

Community
  • 1
  • 1
aL3xa
  • 35,415
  • 18
  • 79
  • 112
  • I should've mentioned that I'm currently passing the data back as a vector of strings (where each string contains just 0 or 1 chars) - I was looking for something 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. – Yang Aug 24 '11 at 07:37