CRC-32: Difference between revisions
→{{header|C++}}: Ranges and constexpr
(→{{header|C++}}: Ranges and constexpr) |
|||
Line 543:
=={{header|C++}}==
<syntaxhighlight lang=cpp>#include <
#include <
#include <cstdint>
#include <numeric>
#include <concepts>
#include <algorithm>
// These headers are only needed for main(), to demonstrate.
#include <iomanip>
#include <iostream>
#include <
inline constexpr auto crc_table = []() {
std::array<std::
[n = std::uint32_t{ 0 }]() mutable {
auto c = n++;
if (c & 1) c = std::uint32_t{ 0xedb88320 } ^ (c >> 1);
else c >>= 1;
}▼
}();
▲ for (auto i = 0; i < 8; ++i)
▲ return checksum;
▲ std::generate(table.begin(), table.end(), byte_checksum{});
▲ return table;
[[nodiscard]] constexpr std::uint32_t crc(const std::ranges::input_range auto& rng)
noexcept requires std::convertible_to<std::ranges::range_value_t<decltype(rng)>, std::uint8_t> {
return ~std::accumulate(std::ranges::begin(rng), std::ranges::end(rng),
~std::uint32_t{ 0 } & std::uint32_t{ 0xff'ff'ff'ffu },
▲ [](std::uint_fast32_t checksum, std::uint_fast8_t value)
▲ { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });
}
int main() {
▲ auto const s = std::string{"The quick brown fox jumps over the lazy dog"};
std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(
}</syntaxhighlight>▼
▲</syntaxhighlight>
{{out}}
<pre>
|