将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
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 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
相关文章:
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- C++ int* 和 char* 字节顺序已交换
- 交换未定义数据类型中的字节顺序
- winsock上的蓝牙,如何删除字节顺序标记
- 将网络字节顺序(大字节序)转换为小字节序
- 将主机字节顺序转换为网络字节顺序有时会导致奇怪的结果
- 当在网络字节顺序中放置双精度时,为什么它是在 4 字节块中完成的
- 使用mysql本机函数进行字节顺序转换
- C++:如何交换wchar_t的字节顺序
- reinterpret_cast接收端的'serializing'数据、字节顺序和对齐方式
- 到Arduino的串行通信的字节顺序
- 使用不带Unicode字节顺序标记的iconv进行字符转换
- 从Byte*到unsigned int的memcpy正在反转字节顺序
- 忽略C++中的字节顺序标记,从流中读取
- iPhone TCP-IP字节顺序映射
- 特定字节顺序的内存c/c++
- 按字节顺序读取UTF-16格式的文件到wstring
- 使用预处理器检查字节顺序
- 确定uint32_t的字节顺序
- 什么可能导致数据包的字节顺序部分混乱?