从 C++ 中的字节数组中检索整数的最佳方法是什么
What is the best way to retreieve an integer from a byte array in C++
现在我以这种方式将 int 转换为字节数组:
int num = 16777215;
char* bytes = static_cast<char*>(static_cast<void*>(&num));
这是最好的方法吗?
另外,如何从该数组中检索 int 值?
如果你想要字节,你使用了错误的转换:
char* bytes = reinterpret_cast<char*>(&num);
反之亦然:
int num = *reinterpret_cast<int*>(bytes);
请注意,通常您不能这样做,char
很特殊,因此您可能需要查找别名。
响应
有没有办法将其直接转换为向量?
你可以做这样的事情:
#include <vector>
#include <cstdint>
template <class T>
std::vector<uint8_t> toByteVector(T value)
{
std::vector<uint8_t> vec = (std::vector<uint8_t>
(reinterpret_cast<uint8_t*>(&value),
(reinterpret_cast<uint8_t*>(&value))+sizeof(T))
);
dumpBytes<T>(vec);
return vec; // RVO to the rescue
}
// just for dumping:
#include <iostream>
#include <typeinfo>
#include <iomanip>
template <class T>
void dumpBytes(const std::vector<uint8_t>& vec)
{
std::cout << typeid(T).name() << ":n";
for (auto b : vec){
// boost::format is so much better for formatted output.
// Even a printf statement looks better!
std::cout << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>(b) << " "
;
}
std::cout << std::endl;
}
int main()
{
uint16_t n16 = 0xABCD;
uint32_t n32 = 0x12345678;
uint64_t n64 = 0x0102030405060708;
toByteVector(n16);
toByteVector(n32);
toByteVector(n64);
return 0;
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将一系列整数放入类的最佳方法是什么?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 从整数向量向量搜索整数向量的最佳算法
- 比较/搜索数组中多个整数的最佳解决方案
- 使用整数的最佳方法
- 可用于存储和管理整数集合的最佳C++数据结构是什么
- 哪种数据结构和设计用于选择最佳整数集
- 在 c++ 中用 '1' 替换整数'0'的最佳方法是什么
- 将浮点数组转换为整数的最佳方式.[替换x64的asm代码]
- 存储和计数字符串或整数重复项的最佳方法是什么
- 保存一组整数的最佳方法
- 从 C++ 中的字节数组中检索整数的最佳方法是什么
- 检查浮点是否为整数的最佳方法
- 检查无符号整数是否没有索引的最佳实践
- 提取整数余数的最佳方法
- 在c++中,防止整数0隐式转换为指针的最佳方法是什么?
- c++中从字符串生成唯一无符号整数的最佳方法是什么?