Search code examples
javascriptnode.jschecksumxordgrams

Checksum XOR calculation in JavaScript


I'm building and UDP server to communicate with GPS devices. It's built in node using dgram.

I have this data to calculate its checksum:

>RGP261222120013-3520041-05908923000176700DF4400;ID=4718;#44E6;*24<

GPS device manual says something like this: Checksum: in hex format, it's calculated by XOR all ASCII codes of the characters composing the message starting with the > and finishing at the last ; (included) but not including the last asterisk

Therefore, the string to calculate the checksum is >RGP261222120013-3520041-05908923000176700DF4400;ID=4718;#44E6;

Device's manual gives an example in C#, and I tried to adapt it to JavaScript:

C# example

public static string calculateChecksum(string data)
{
  int r;
  int calc = 0;
  byte caracter;
  string calculated_checksum; 
  for (r = 0; r < data.Length; r++) {
    if ((data[r] == '*') && (data[r-1] == ';')) break;
    caracter = (byte)data[r];
    calc = calc ^ (byte)caracter; 
  }
  calculated_checksum = calc.ToString("X"); 
  return calculated_checksum;
}

My JS adaptation so far

export const calculateChecksum = (packet) => {
  const len = packet.length;
  const position = packet.indexOf(';*') + 1;
  const packetToCheck = packet.slice(0, position);

  let checksum = 0;

  for (let char of packetToCheck) {
    checksum ^= char.charCodeAt(0);
  };

  return checksum.toString(16);
}

From other software I get that the response to that data is:

>ACK;ID=4718;#44E6;*26<

Being 26 the calculated checksum (and this is the right result). The device will repeat the message if the checksum sent by the server is wrong.

With my approach, I'm getting a result of 24.

I really don't know how to move on.


Solution

  • I was misunderstanding the documentation. I don't delete the question so everyone has access to the function.