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

How to unpack numbers in cpp if they are pack at python using struct.pack(fmt, v1, v2, ...)

本文关键字:v1 fmt pack struct v2 pyth 解压缩 cpp 数字 如果      更新时间:2023-10-16

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

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

它返回

'xc8x01x00x00x00x00x00x00{x00x00x00x00x00x00x00'

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

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

#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::string input = std::string("xc8x01x00x00x00x00x00x00{x00x00x00x00x00x00x00", 16);
for ( size_t i = 0; i < input.size() / 8; i++ )
{
int64_t value;
memcpy(&value, &input[i*8], 8);
std::cout << value << "n";
}
}

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

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

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

#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

我在这里没有处理字节序。只是假设它们是相同的。但是,如果您想要它,只需使用该类型的大小交换字节即可。