Last active
February 10, 2020 14:08
-
-
Save mnrn/3cd682801a260f642c637ed7115d9a4a to your computer and use it in GitHub Desktop.
checksum
This file contains hidden or 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 <sys/types.h> // for network | |
| static constexpr u_int16_t checksum(const u_int16_t* data, const size_t n) | |
| { | |
| u_int32_t sum = 0; | |
| // The inner loop. | |
| for (size_t i = n; i > 1; i -= 2, data++) { | |
| sum += *data; | |
| } | |
| // Add left-over byte, if any. | |
| if (n & 0x01) { | |
| sum += *reinterpret_cast<const u_int8_t*>(data); | |
| } | |
| // Fold 32-bit sum to 16bits. | |
| while (sum >> 16) { | |
| sum = (sum & 0xffff) + (sum >> 16); | |
| } | |
| return static_cast<u_int16_t>(~sum); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment