Skip to content

Instantly share code, notes, and snippets.

@t0rr3sp3dr0
Last active July 23, 2022 05:11
Show Gist options
  • Save t0rr3sp3dr0/0e2cd1c25b529e80ff7a0bab0da9c50b to your computer and use it in GitHub Desktop.
Save t0rr3sp3dr0/0e2cd1c25b529e80ff7a0bab0da9c50b to your computer and use it in GitHub Desktop.
#include <iostream>
constexpr uint8_t m_len = 40;
constexpr uint8_t crc_len = 7;
constexpr uint8_t msb_shift = m_len + crc_len - 1;
constexpr uint8_t g_len = 8;
constexpr uint8_t g_shift = m_len + crc_len - g_len;
constexpr uint8_t g = (1 << 7) | (1 << 3) | (1 << 0); // G(x) = x^7 + x^3 + 1
constexpr uint8_t crc7_impl(uint64_t crc, uint64_t msb, uint64_t msk, uint8_t iter) {
return iter == 0 ? (uint8_t) crc : crc7_impl(crc & msb ? crc ^ msk : crc, msb >> 1, msk >> 1, iter - 1);
}
constexpr uint8_t crc7(uint64_t m) {
return crc7_impl(m << crc_len, (uint64_t) 1 << msb_shift, (uint64_t) g << g_shift, g_shift + 1);
}
int main() {
// 0100000000000000000000000000000000000000 -> 1001010
std::cout << ((int) crc7(274877906944)) << " = " << 74 << std::endl;
// 0101000100000000000000000000000000000000 -> 0101010
std::cout << ((int) crc7(347892350976)) << " = " << 42 << std::endl;
// 0001000100000000000000000000100100000000 -> 0110011
std::cout << ((int) crc7(73014446336)) << " = " << 51 << std::endl;
// 0000000000000000000000000000000000000000 -> 0000000
std::cout << ((int) crc7(0)) << " = " << 0 << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment