Last active
December 10, 2021 08:44
-
-
Save bgamari/4676895 to your computer and use it in GitHub Desktop.
C++11 Fletcher checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#include <cstring> | |
#include <type_traits> | |
constexpr const uint16_t csum(const char* s, size_t n, size_t i, uint16_t sum1, uint16_t sum2) { | |
return (i <= n) ? csum(s, n, i+1, (sum1 + s[i]) % 255, (sum2 + sum1) % 255) : ((sum2 << 8) | sum1); | |
} | |
constexpr const uint16_t operator "" _csum(const char* s, size_t n) { | |
return csum(s, n, 0, 0, 0); | |
} | |
#define CSUM(a) std::integral_constant<uint16_t, a##_csum>::value | |
int main() { | |
printf("%d\n", CSUM("asdfada")); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment