Macro Wong
Macro Wong

Reputation: 43

Is there any solution for calculate checksum?

I'm writing a SerialPort tool, And I got a problem that I don't know how to calculate the checksum...

For example:

Flag COMM ID COMM Length Data Remain Sum
0x55 0x00000003 0x0000001c 32bit *3 0x00000000 0xFFFFFFDF

The Data:

Remain Sub-Command Remain
0x00000000 0x00000002 0x00000000

The Calculation method:
checksum, SUM=~((DWORD) COMM ID + (DWORD) COMM Length + (DWORD) Data + (DWORD)Sub-Command + (DWORD) Remain) +1

The result:
55 03 00 00 00 1C 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 DF FF FF FF

How can I get the sum(like 0xFFFFFFDF) with C#?

Upvotes: 0

Views: 207

Answers (1)

Rook
Rook

Reputation: 6145

You seem to have already answered your own question, more or less, though your calculation method mentions both "data" and "subcommand", even though "subcommand" is part of "data".

int commId = 0x00000003;
int length = 0x0000001c;
int subcommand = 0x00000002;
int remain = 0x00000000;
            
// you said:
// ~((DWORD) COMM ID + (DWORD) COMM Length + (DWORD) Data + (DWORD)Sub-Command + (DWORD) Remain) +1
// you probably wanted Remain + Sub-Command + Remain though,
// as that is what Data is defined as.
int csum = ~(commId + length + remain + subcommand + remain) + 1;
            
Console.WriteLine(csum.ToString("X"));

produces the result -33, with the next value FFFFFFDF.

DWORD is simply a 32-bit integer, just like the standard C# int type. ~ is the unary negation operator.

Upvotes: 2

Related Questions