c++ - 将算术类型转换为 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
?
解决方案
是否有可能有一个简单的模板函数适用于所有算术类型,如 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;
}
推荐阅读
- java - 是否可以表明 Web 会话对单个站点(或页面)有效?
- flutter - SearchDelegate 查询更改
- amazon-web-services - AWS amplify graphql appsync - 如何替换数组而不是追加?
- django - 如何在 Django 查询中为每个单词插入通配符?
- css - 更改选择输入选项的字体颜色 R Shiny
- sql - 按 2 列对项目进行分组
- google-sheets - 将文本转换为方程式并在 Google 表格中返回总和结果
- ios - Bundle.main.preferredLocalizations 是否有可能返回多个元素?
- java - 让活动全屏?
- python - 如何实现此脚本的代理?