[英]C++ How to convert a big integer in std::string form to byte/char-array/vector
[英]Convert Integer to 4 byte ungisned char vector (in Big endian byte order)
假设,我想在 4 个字节的二进制文件(已经加载到向量中)中写入十进制 31,所以我必须写为 00 00 00 1f,但我不知道如何将十进制数转换为十六进制字符串(的4字节)
因此,无符号字符向量中的预期十六进制是:
0x00 0x00 0x00 0x1f // int value of this is 31
为此,我尝试了以下操作:
std::stringstream stream;
stream << std::setfill('0') << std::setw(sizeof(int) * 2) << std::hex << 31;
cout << stream.str();
输出:
0000001f
上面的代码行给出了字符串格式的输出,但我希望它以'0x'格式的无符号字符向量,所以我的输出向量在转换后应该有元素为0x00 0x00 0x00 0x1F。
无需担心字节顺序,您可以将int
值复制到适当大小的字符缓冲区中。 这个缓冲区可以是向量本身。
也许是这样的:
std::vector<uint8_t> int_to_vector(unsigned value)
{
// Create a vector of unsigned characters (bytes on a byte-oriented platform)
// The size will be set to the same size as the value type
std::vector<uint8_t> buffer(sizeof value);
// Do a byte-wise copy of the value into the vector data
std::memcpy(buffer.data(), &value, sizeof value);
return buffer;
}
向量中的字节顺序将始终按主机本机顺序排列。 如果强制要求特定顺序,则需要使用按位运算将多字节值的每个字节复制到数组的特定元素中(不能使用std::memcpy
)。
另请注意,如果uint8_t
不是unsigned char
的别名,则此函数将破坏严格别名。 并且uint8_t
是可选类型,有些平台没有 8 位实体(尽管它们并不常见)。
对于特定于字节序的变体,其中一个字节的每个值都被一个一个地提取并添加到向量中,可能是这样的:
std::vector<uint8_t> int_to_be_vector(unsigned value)
{
// Create a vector of unsigned characters (bytes on a byte-oriented platform)
// The size will be set to the same size as the value type
std::vector<uint8_t> buffer(sizeof value);
// For each byte in the multi-byte value, copy it to the "correct" place in the vector
for (size_t i = buffer.size(); i > 0; --i)
{
// The cast truncates the value, dropping all but the lowest eight bits
buffer[i - 1] = static_cast<uint8_t>(value);
value >>= 8;
}
return buffer;
}
您可以使用循环一次提取原始数字的一个字节并将其存储在向量中。
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
using u8 = std::uint8_t;
using u32 = std::uint32_t;
std::vector<u8> GetBytes(const u32 number) {
const u32 mask{0xFF};
u32 remaining{number};
std::vector<u8> result{};
while (remaining != 0u) {
const u32 bits{remaining & mask};
const u8 res{static_cast<u8>(bits)};
result.push_back(res);
remaining >>= 8u;
}
std::reverse(std::begin(result), std::end(result));
return result;
}
int main() {
const u32 myNumber{0xABC123};
const auto bytes{GetBytes(myNumber)};
std::cout << std::hex << std::showbase;
for (const auto b : bytes) {
std::cout << static_cast<u32>(b) << ' ';
}
std::cout << std::endl;
return 0;
}
这个程序的输出是:
0xab 0xc1 0x23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.