Skip to content

Instantly share code, notes, and snippets.

@mnrn
Last active February 10, 2020 14:08
Show Gist options
  • Select an option

  • Save mnrn/3cd682801a260f642c637ed7115d9a4a to your computer and use it in GitHub Desktop.

Select an option

Save mnrn/3cd682801a260f642c637ed7115d9a4a to your computer and use it in GitHub Desktop.
checksum
#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