如果使用struct.pack(fmt,v1,v2,...)在python打包,如何在cpp中解压缩数字

问题描述 投票:1回答:2

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

struct.pack("<2q", 456, 123)

它回来了

'\xc8\x01\x00\x00\x00\x00\x00\x00{\x00\x00\x00\x00\x00\x00\x00'

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

python c++ serialization encoding
2个回答
1
投票

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

#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
投票

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

Format  C Type      Python type     Standard size
q      long long    integer         8

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

#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';
}

打印:

456,123

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

© www.soinside.com 2019 - 2024. All rights reserved.