将 int 打包在一个字符串中
Pack int in a string
我正在尝试将此序列从Python转换为C++。
bytesString = struct.pack('!l', value)
如何使用字节移位将整数值打包到 std::string 中?
易于维护的方法(与字节序无关)
将基元类型的值"编码"为字节序列的典型方法是使用一个简单的std::copy
:
#include <string>
#include <iostream>
#include <iomanip>
template <typename T>
std::string pack(const T val)
{
std::string bytes(sizeof(T), ' ');
std::copy(
reinterpret_cast<const char*>(&val),
reinterpret_cast<const char*>(&val) + sizeof(T),
bytes.begin()
);
return bytes;
}
int main()
{
int x = 42;
std::string bytes{pack(x)};
std::cout << std::noshowbase << std::hex << std::setfill('0');
for (auto c : bytes)
std::cout << "0x" << std::setw(2) << +c << ' ';
// ^ may need tweaking for values above 127; not sure
}
// On my little-endian system with 32-bit int:
// "0x2a 0x00 0x00 0x00"
(现场演示)
可能需要 C++11 严格,因为在此之前std::string
不是正式连续的。我显然在main
中使用了 C++11 语法,但这可以稍微改变一下。
易于维护的方法(网络字节顺序)
如果您希望结果始终按网络字节顺序排列(这与 Python 表达式中 !
的使用相匹配),您可以先应用htonl
:
std::string bytes{pack(htonl(x))};
(仅reinterpret_cast
整个值(而不是复制)的解决方案存在潜在的对齐和锯齿问题。
最佳方法(网络字节顺序)
如果你的代码处于一个紧密循环中,并且你不想要字节序转换和复制,那么你可以考虑一个遍历班次的循环:
#include <string>
#include <climits>
#include <iostream>
#include <iomanip>
template <typename T>
std::string pack_in_network_order(const T val)
{
const size_t NBYTES = sizeof(T);
std::string bytes(NBYTES, ' ');
for (size_t i = 0; i < NBYTES; i++)
bytes[NBYTES - 1 - i] = (val >> (i * CHAR_BIT)) & 0xFF;
return bytes;
}
int main()
{
int x = 42;
std::string bytes{pack_in_network_order(x)};
std::cout << std::noshowbase << std::hex << std::setfill('0');
for (auto c : bytes)
std::cout << "0x" << std::setw(2) << +c << ' ';
}
// On my system with 32-bit int:
// "0x00 0x00 0x00 0x2a"
(现场演示)
(我使用 CHAR_BIT
实现可移植性,但硬编码0xFF
作为值掩码。您需要修复此问题。
相关文章:
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何检查一个c++字符串中有多少相同的字符/数字
- 获取用C/C++打印的最后一个字符串
- cin >> int 给定一个字符串将 int 赋值为 0
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- C++为 void 指针分配一个字符串
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 如何在另一个字符串的x位置插入一个字符串?
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 在另一个字符串中插入文件扩展名之前的字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- C++自定义流操纵器,用于更改流上的下一个字符串
- 从类返回一个字符串 — 奇怪的行为
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 你能从"volatile const char*"构造一个字符串吗?(不使用`const_cast`