将长整数转换为字符数组的最安全的方法是什么

jet*_*ett 2 c++ arrays casting reinterpret-cast c++11

现在我有这个代码:

uint64_t buffer = 0;
const uint8_t * data = reinterpret_cast<uint8_t*>(&buffer);
Run Code Online (Sandbox Code Playgroud)

这样做有效,但由于悬挂指针(看起来也很难看)似乎有风险.我不想坐在那里的裸指针.我想做这样的事情:

uint64_t buffer = 0;
const std::array<uint8_t, 8> data = partition_me_softly(buffer);
Run Code Online (Sandbox Code Playgroud)

是否有和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;
}
Run Code Online (Sandbox Code Playgroud)

这样你可以使用更多类型,如:

uint64_t buffer = 0;
ScalarToByteArray<uint8_t>(buffer);
Run Code Online (Sandbox Code Playgroud)

Col*_*nee 5

如果要在字节数组中存储整数,最好的方法可能是将整数转换为a 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;
}
Run Code Online (Sandbox Code Playgroud)