如何在 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, ...)
在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
我在这里没有处理字节序。只是假设它们是相同的。但是,如果您想要它,只需使用该类型的大小交换字节即可。
相关文章:
- 用C++20 fmt限制结果的总大小
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- fmt 与 Howard Hinnant 的日期:为什么从 fmt::to_string "{}"?FMT 和日期的最佳实践?
- 如何在 cpp 中解压缩数字,如果它们是使用 struct.pack(fmt, v1, v2, ..) 打包在 pyth
- 我不能在 c++ 上使用 fmt 库标头
- <int> 使用 fmt 库将向量转换为字符串
- 调用boost v1.58中的函数时出现模板名称使用无效错误
- C++fmt库,只使用格式说明符格式化单个参数
- 使用{fmt}库打印
- 为什么 {fmt} 比 std::stringstream 慢?
- Affectiva 可以连接 Kinect v1 吗?
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- 使用 CMake 构建 {fmt} 时出现问题
- 如何使用wchar_t为 fmt 编写格式化程序?
- 如何获得 fmt::format 与wchar_t一起使用?
- 从 {fmt} 获得最佳性能
- boost::v1.59 和 v1.60 之间的序列化存档版本
- 低功耗 ESP32 + 具有深度睡眠模式的 LoRa (TTGO LoRa32 OLED 板 V1.0).