首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用struct.pack(fmt,v1,v2,...)在python中解压cpp中的数字

如何使用struct.pack(fmt,v1,v2,...)在python中解压cpp中的数字
EN

Stack Overflow用户
提问于 2018-09-14 21:23:36
回答 2查看 218关注 0票数 1

在python中,我使用struct对数字进行编码

代码语言:javascript
运行
复制
struct.pack("<2q", 456, 123)

它返回

代码语言:javascript
运行
复制
'\xc8\x01\x00\x00\x00\x00\x00\x00{\x00\x00\x00\x00\x00\x00\x00'

在cpp中,我如何将这样的字符串解码为整数元组?

EN

回答 2

Stack Overflow用户

发布于 2018-09-14 21:32:11

解压该字符串应该相当简单,只需将字节复制到适当大小的整数中即可:

代码语言:javascript
运行
复制
#include <iostream>
#include <string>
#include <cstring>

int main()
{
  std::string input = std::string("\xc8\x01\x00\x00\x00\x00\x00\x00{\x00\x00\x00\x00\x00\x00\x00", 16);
  for ( size_t i = 0; i < input.size() / 8; i++ )
  {
      int64_t value;
      memcpy(&value, &input[i*8], 8);
      std::cout << value << "\n";
  }
}
票数 1
EN

Stack Overflow用户

发布于 2018-09-14 21:34:27

q是很长的64位有符号整数。来自https://docs.python.org/3/library/struct.html

代码语言:javascript
运行
复制
Format  C Type      Python type     Standard size
q      long long    integer         8

您可以读取此缓冲区并复制到一个2长的数组中(使用stdint.h定义的64位)

代码语言:javascript
运行
复制
#include <iostream>
#include <strings.h>
#include <stdint.h>

int main()
{
 // you're supposed to get that when reading the buffer from a file for instance:
 const unsigned char buffer[] = {0xc8,0x01,0x00,0x00,0x00,0x00,0x00,0x00,'{',0x00,0x00,0x00,0x00,0x00,0x00,0x00};
 int64_t array[2];
 memcpy(array,buffer,sizeof(array));
 std::cout << array[0] << "," << array[1] << '\n';
}

打印:

代码语言:javascript
运行
复制
456,123

我在这里没有处理字符顺序。只是假设它们是一样的。但是如果你想这样做,只需使用类型的大小交换字节,就可以了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52332988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档