Last active
September 25, 2022 17:55
-
-
Save israellot/6cee3aebfc43578b85179ddbd8f944d7 to your computer and use it in GitHub Desktop.
Simple Big-endian 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
// 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