Skip to content

Instantly share code, notes, and snippets.

@Buggem
Created October 11, 2026 06:13
Show Gist options
  • Select an option

  • Save Buggem/ce3d105a39418bbb1cf57d17ee9eb81f to your computer and use it in GitHub Desktop.

Select an option

Save Buggem/ce3d105a39418bbb1cf57d17ee9eb81f to your computer and use it in GitHub Desktop.
Simple function to get the internet checksum of data
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
uint16_t internetChecksum(const void* x, size_t size)
{
uint64_t sum = 0;
const uint8_t* ptr = (uint8_t*)x; // really not neccasary, just a simple cast
size_t i = 0; // iterator declared outside of loop to respect C90 standards
for(; i < size; i++) // while the iterator still isn't at the end
{
if(i & 1) // if i is odd
sum += (uint64_t)ptr[i] << 8; // add ptr[i] shifted left by 8 to the sum
else // else (if i is even)
sum += (uint64_t)ptr[i]; // add ptr[i] to the sum
}
while(sum >> 16) // while sum still can't be losslessly fit into an unsigned 16-bit int
sum = (sum & 0xffff) + (sum >> 16); // keep "folding" sum into 16-bits
#if (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || defined(HOST_CHECKSUM)
return (uint16_t)~sum; // return normal sum, able to be directly memcpy'd
#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
return (uint16_t)~( // return byte-swapped sum, able to be directly memcpy'd
((sum >> 8) & 0x00ff) |
((sum << 8) & 0xff00)
);
#else
#error "Unknown byte order - define HOST_CHECKSUM if this is a little-endian target or you want to manually byte-swap"
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment