livox_mid360_core
C++ driver library for the Livox Mid-360 LiDAR
Loading...
Searching...
No Matches
crc.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
13#pragma once
14
15#include <array>
16#include <cstddef>
17#include <cstdint>
18#include <span>
19
21{
22
23namespace detail
24{
25
26consteval std::array<std::uint16_t, 256> make_crc16_table()
27{
28 std::array<std::uint16_t, 256> t{};
29 for (std::uint32_t i = 0; i < 256; ++i) {
30 auto c = static_cast<std::uint16_t>(i << 8);
31 for (int k = 0; k < 8; ++k) {
32 const std::uint32_t shifted = static_cast<std::uint32_t>(c) << 1;
33 c = static_cast<std::uint16_t>((c & 0x8000u) ? (shifted ^ 0x1021u) : shifted);
34 }
35 t[i] = c;
36 }
37 return t;
38}
39
40consteval std::array<std::uint32_t, 256> make_crc32_table()
41{
42 // Reflected form of 0x04C11DB7 is 0xEDB88320.
43 std::array<std::uint32_t, 256> t{};
44 for (std::uint32_t i = 0; i < 256; ++i) {
45 std::uint32_t c = i;
46 for (int k = 0; k < 8; ++k) {
47 c = (c & 1u) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
48 }
49 t[i] = c;
50 }
51 return t;
52}
53
54inline constexpr auto kCrc16Table = make_crc16_table();
55inline constexpr auto kCrc32Table = make_crc32_table();
56
57} // namespace detail
58
60[[nodiscard]] constexpr std::uint16_t crc16_ccitt_false(
61 std::span<const std::byte> data, std::uint16_t state = 0xFFFF) noexcept
62{
63 for (std::byte b : data) {
64 const auto idx = static_cast<std::uint8_t>((state >> 8) ^ static_cast<std::uint8_t>(b));
65 state = static_cast<std::uint16_t>((state << 8) ^ detail::kCrc16Table[idx]);
66 }
67 return state;
68}
69
72[[nodiscard]] constexpr std::uint32_t crc32(
73 std::span<const std::byte> data, std::uint32_t state = 0) noexcept
74{
75 std::uint32_t c = state ^ 0xFFFFFFFFu;
76 for (std::byte b : data) {
77 c = detail::kCrc32Table[(c ^ static_cast<std::uint8_t>(b)) & 0xFFu] ^ (c >> 8);
78 }
79 return c ^ 0xFFFFFFFFu;
80}
81
82} // namespace livox::mid360::crc
CRC-16 and CRC-32 as defined by the Mid-360 communication protocol (crc.hpp).
Definition crc.hpp:21
constexpr std::uint16_t crc16_ccitt_false(std::span< const std::byte > data, std::uint16_t state=0xFFFF) noexcept
Incremental CRC-16/CCITT-FALSE. Pass the previous result as state to continue.
Definition crc.hpp:60
constexpr std::uint32_t crc32(std::span< const std::byte > data, std::uint32_t state=0) noexcept
Incremental CRC-32 (zlib-compatible).
Definition crc.hpp:72