Skip to content

Instantly share code, notes, and snippets.

@israellot
Last active September 25, 2022 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israellot/6cee3aebfc43578b85179ddbd8f944d7 to your computer and use it in GitHub Desktop.
Save israellot/6cee3aebfc43578b85179ddbd8f944d7 to your computer and use it in GitHub Desktop.
Simple Big-endian Checksum
// Compute a 32-bit big-endian checksum on the N-byte buffer. If the
// buffer is not a multiple of 4 bytes length, compute the sum that would
// have occurred if the buffer was padded with zeros to the next multiple
// of four bytes.
public static uint Checksum(ReadOnlySpan<byte> arr)
{
if (arr.Length == 0) return 0;
uint sum0 = 0, sum1 = 0, sum2 = 0, sum = 0, N = (uint)arr.Length;
int z = 0;
while (N >= 4)
{
sum0 += arr[z + 0];
sum1 += arr[z + 1];
sum2 += arr[z + 2];
sum += arr[z + 3];
z += 4;
N -= 4;
}
sum += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
switch (N & 3)
{
case 3:
sum += (uint)(arr[z + 2]) << 8;
sum += (uint)(arr[z + 1]) << 16;
sum += (uint)(arr[z + 0]) << 24;
break;
case 2:
sum += (uint)(arr[z + 1]) << 16;
sum += (uint)(arr[z + 0]) << 24;
break;
case 1:
sum += (uint)(arr[z + 0]) << 24;
break;
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment