R equivalent for numpy 'frombuffer'

To decode a binary response from a socket connection in Python, I would do:

import numpy as np

answer= b"\x80\x8eaS\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x80\x8eaS\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00"

datatype = [('da_0', '<i8'), ('i8_1', '<i8')]

np.frombuffer(answer, datatype)

which outputs

>>>array([(1398902400, 1), (1398902400, 1)], 
  dtype=[('da_0', '<i8'), ('i8_1', '<i8')])

I struggled with the unpack () function (from {pack}) in R to reproduce the same result, but so far without success.

Any idea would be greatly appreciated!

+4
source share
1 answer

In R you can use readBinfor join or for raw vector

answer=as.raw(c(
0x80,0x8e,0x61,0x53,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x80,0x8e,0x61,0x53,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00))


readBin(answer[1:16],"integer", size=8,n=2, endian="little")
# [1] 1398902400          1 
readBin(answer[17:32],"integer", size=8, n=2, endian="little")
# [1] 1398902400          1

If your answer is in a connection object, you don’t have to worry about indexing to extract the correct part of the raw vector. You can just read from the binary connection and it will track the indexing.

+1

Source: https://habr.com/ru/post/1548513/


All Articles