现在我有这段代码:
uint64_t buffer = 0;
const uint8_t * data = reinterpret_cast<uint8_t*>(&buffer);
这行得通,但由于悬挂指针(而且看起来也很丑),它似乎有风险。我不想到处都是裸指针。我想做这样的事情:
uint64_t buffer = 0;
const std::array<uint8_t, 8> data = partition_me_softly(buffer);
是否有 c++11 风格的构造允许我将其放入安全的容器中,最好是 std::array
来自 unsigned int
之类的这不会引起开销?
如果不是,改进此代码以使其更安全的理想方法是什么?
所以我修改了 dauphic 的答案,使其更通用一些:
template <typename T, typename U>
std::array<T, sizeof(U) / sizeof(T)> ScalarToByteArray(const U v)
{
static_assert(std::is_integral<T>::value && std::is_integral<U>::value,
"Template parameter must be a scalar type");
std::array<T, sizeof(U) / sizeof(T)> ret;
std::copy((T*)&v, ((T*)&v) + sizeof(U), ret.begin());
return ret;
}
这样您就可以将它用于更多类型,例如:
uint64_t buffer = 0;
ScalarToByteArray<uint8_t>(buffer);
最佳答案
如果您想将整数存储在字节数组中,最好的方法可能是将整数转换为 uint8_t*
并将其复制到 std::array
。在某些时候您将不得不使用原始指针,因此最好的选择是将操作封装到一个函数中。
template<typename T>
std::array<uint8_t, sizeof(T)> ScalarToByteArray(const T value)
{
static_assert(std::is_integral<T>::value,
"Template parameter must be a scalar type");
std::array<uint8_t, sizeof(T)> result;
std::copy((uint8_t*)&value, ((uint8_t*)&value) + sizeof(T), result.begin());
return result;
}
关于c++ - 将长整数转换为字符数组的最安全方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19804402/