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

标签 c++ arrays c++11 casting reinterpret-cast

现在我有这段代码:

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/

相关文章:

c++ - 将回调函数中的对象引用传递给 std::thread

c++ - std::bind 绑定(bind)函数

c++ - 如何在调用另一个宏时使用宏参数?

c++ - 一个对象的两个指针。删除了一个指针,对象还在

arrays - 如何在 Rust 中将切片作为数组获取?

java - 如何从数组列表中获取不同的值?

c++ - 如何实现STL容器中对象的快速释放?

c++ - 将静态全局变量声明为内联是否有意义?

c++ - 为什么我的 ListBox 中仍然有字符串,即使在使用循环单独删除它们之后?

javascript - Wikitude Javascript SDK 中 MarkerList 数组的结构