【问题标题】:R equivalent for numpy 'frombuffer'numpy 'frombuffer' 的 R 等效项
【发布时间】:2014-07-15 16:00:33
【问题描述】:

要从 Python 中的套接字连接解码二进制答案,我会这样做:

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)

哪个输出

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

我一直在使用 R 中的 unpack() 函数(来自 {pack})来重现相同的结果,但直到现在都没有成功。

任何想法将不胜感激!

【问题讨论】:

  • 您是否需要知道如何从套接字获取响应,或者您已经在 R 中得到响应?如果是这样,你是如何存储它的?
  • 我已经有了通过 readBin() 得到的答案,并存储在“原始”类对象中。我能够解析标题(其中包含列数、行数、数据类型等信息),但至于我目前卡住的内容。
  • 如果我没看错你的python,你的数字是64位整数吗?我不太了解dtype 规范。您能否在您的问题中对此进行扩展,并可能将您的一些原始数据与您认为其中的数字一起转储?

标签: python r numpy binary-data


【解决方案1】:

在 R 中,您可以在连接或原始向量上使用 readBin

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

如果您的响应是在连接对象中,那么您不必担心索引来提取原始向量的正确部分。您可以从二进制连接中读取,它会跟踪索引。

【讨论】:

  • 它就像一个魅力。我可以使用从标题中获得的列数据类型来指定模式。那太好了。谢谢!
猜你喜欢
  • 2017-02-18
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2014-09-05
  • 2012-01-12
  • 1970-01-01
相关资源
最近更新 更多