4

To decode a binary answer 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 have been battling with the unpack() function (from {pack}) in R to reproduce the same result but unsuccessfully until now.

Any idea would be much appreciated !

Alexis Matelin
  • 194
  • 1
  • 9
  • Do you need to know how to get the response from a socket or have you already got that in R? If so, how are you storing it? – Spacedman Jul 15 '14 at 16:34
  • I already have the answer which I get with readBin() and is stored in a class "raw" object. I'm able to parse the header (which contains information like number of columns, number of rows, data type etc.) but as for the content I'm currently stuck. – Alexis Matelin Jul 15 '14 at 16:51
  • If I read your python right, your numbers are 64-bit integers? I don't really understand the `dtype` spec. Could you expand on that in your question and possibly dump some of your raw data with the numbers you think are in it? – Spacedman Jul 15 '14 at 16:54

1 Answers1

2

In R, you can use readBin on a connection, or on a 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 response is in a connection object then you wouldn't have to worry about the indexing to extract the correct portion of the raw vector. You could just read from the binary connection and it will keep track of indexing.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • And it works like a charm. I can use the columns data type I get from the header to specify the mode. That's just great. Thank you ! – Alexis Matelin Jul 15 '14 at 17:43