首页 > 解决方案 > 将算术类型转换为 std::array 的最简单方法在 C++ 中

问题描述

我有一个计算 CRC64 并将其返回为的函数uint64_t

static inline uint64_t crc64(uint64_t crc, const uint8_t *s, size_t l)
{
    const uint8_t * end = s + l;

    for (const uint8_t * p = s; p != end; ++p)
    {
        const uint8_t byte = *p;
        crc = crc64_tab[(uint8_t)crc ^ byte] ^ (crc >> 8);
    }

    return crc;
}

我想将结果转换为std::array<sizeof(uint8_t)>并使其独立于字节序(小/大字节序)。在 C++ 中是否有一种简单而优雅的方法来做到这一点?

是否有可能有一个简单的模板函数适用于所有算术类型,比如uintN_t

标签: c++templatesendiannessstdarray

解决方案


是否有可能有一个简单的模板函数适用于所有算术类型,如 uintN_t?

#include <cstddef>
#include <cstdint>
#include <array>

template< typename T >
std::array<std::uint8_t, sizeof(T)> to_array(T value)
{
    std::array<std::uint8_t, sizeof(T)> result;

    for (std::size_t i{ sizeof(T) }; i; --i)
        result[i - 1] = value >> ((sizeof(T) - i) * 8);

    return result;
}

推荐阅读