# Thread: [RESOLVED] MY UDP Checksum method. How can I make it better.

1. ## [RESOLVED] MY UDP Checksum method. How can I make it better.

I created this method to calculate the checksum for a UDP packet. I believe it works but I am sure it can be done a LOT better.

Code:
```static ushort GetChecksum (ref byte[] packet)
{
uint sum = 0;
int indexEnd = packet.Length -1;

if (packet.Length%2 !=0)
{
indexEnd--;
sum+= (uint)packet[^1];
};

for (int index=0; index < indexEnd; index+=2 )
{

byte[] shortAsBytes = packet[(index)..(index+2)];
if (BitConverter.IsLittleEndian)
Array.Reverse(shortAsBytes);
sum+=BitConverter.ToUInt16(shortAsBytes);

}

if (sum> ushort.MaxValue)
{
uint high = sum >> 16;
sum+=high;
}

return (ushort)~sum;
}```
Any suggestions welcome.

2. ## Re: MY UDP Checksum method. How can I make it better.

To answer my own question, I can probably replace this.
Code:
```int indexEnd = packet.Length -1;

if (packet.Length%2 !=0)
{
indexEnd--;
sum+= (uint)packet[^1];
};

for (int index=0; index < indexEnd; index+=2 )```
with

Code:
```
if (packet.Length%2 !=0) sum+= (uint)packet[^1];

for (int index=0; index < packet.Length -1; index+=2 )```

3. ## Re: MY UDP Checksum method. How can I make it better.

I don't think those two code segments are equal.
In the first case you loop through packet.Length - 1 if the packet length is even, or you loop through packet.Length - 2 if the length is odd.

In the second case you're always looping through packet.Length - 1, regardless of whether it is even or odd, so you include a byte past the end of the packet to your checksum if the packet.Length is odd.

4. ## Re: MY UDP Checksum method. How can I make it better.

Well they are in truth not. There was no need to decrement indexEnd again if the length of packet byte array was odd.
It was extra code that was not needed. It almost meant I can remove the indexEnd variable.

Can you point out a way to improve the algorithm or code?

I can laos change this.
Code:
```if (sum> ushort.MaxValue)
{
uint high = sum >> 16;
sum+=high;
}```
to

Code:
`if (sum> ushort.MaxValue) sum+ = (sum >> 16);`
Also should I explicitly cast the result of BitConverter.ToUint16?
Code:
`sum+=BitConverter.ToUInt16(shortAsBytes);`

5. ## Re: MY UDP Checksum method. How can I make it better.

You can check out some previous art like Adler-32 checksum (the checksum used by zlib).

Here is one with SSE3/AVX2 optimizations for .NET 5 on input above 16 bytes which will smoke anything you produces on the subject I suppose.

cheers,
</wqw>

6. ## Re: MY UDP Checksum method. How can I make it better.

Thank you. I will take a look.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•