将Integer转换为4字节的unsined字符矢量(按大端字节顺序)

Convert Integer to 4 byte ungisned char vector (in Big endian byte order)

本文关键字:字节 顺序 字符 转换 Integer unsined      更新时间:2023-10-16

假设,我想在一个二进制文件(已经加载到向量中(中用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 0x1F后应该有元素。

在不考虑endianness的情况下,您可以将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