8-bit XOR checksum using Javascript

2019-08-15 08:01发布

问题:

I'm trying to mimic a windows application that formats a message and sends it over UART via USB to a device that shows that message.

The application calculates a checksum and pastes that after the message, otherwise the device will not accept the command. The checksum is NOT a crc8 checksum, but what is it, then?

Using a USB monitor, I've seen the following test cases:

ASCII: <L1><PA><IB><MA><WC><OM>Test!
HEX: 3c4c313e3c50413e3c49423e3c4d413e3c57433e3c4f4d3e5465737421
Checksum: 6A

ASCII: <L1><PA><IB><MA><WC><OM>Testa!
HEX: 3c4c313e3c50413e3c49423e3c4d413e3c57433e3c4f4d3e546573746121
Checksum: 0B

ASCII: <L1><PA><IB><MA><WC><OM>Test some more
HEX: 3c4c313e3c50413e3c49423e3c4d413e3c57433e3c4f4d3e5465737420736f6d65206d6f7265
Checksum: 4A

ASCII: <L1><PA><IE><MA><WC><OE>[SPACE]
HEX: 3c4c313e3c50413e3c49453e3c4d413e3c57433e3c4f453e20
Checksum: 52

This website returns the correct checksum in the first row (CheckSum8 Xor). I'm trying to mimic that functionality. (Note: the website freaks out when you send the ASCII values because it contains <> characters. Use the HEX values instead!)

Currently, my code does this:

let hex = ascii2hex('<L1><PA><IB><MA><WC><OM>Test!') // or one of the other ascii values
let checksum = chk8xor(hex)
console.log(checksum)

function ascii2hex(str) {
  var arr = [];
  for (var i = 0, l = str.length; i < l; i ++) {
    var hex = Number(str.charCodeAt(i)).toString(16);
    arr.push(hex);
  }
  return arr;
}

function chk8xor(byteArray) {
  let checksum = 0x00
  for(let i = 0; i < byteArray.length - 1; i++)
    checksum ^= byteArray[i]
  return checksum
}

(javascript)

The code works, but returns an incorrect checksum. For instance, the first test case returns 50 instead of 6A.

I'm sure I'm missing something simple.
What am I doing differently than the website I mentioned above?

回答1:

You don't need any "hex" strings here, just take the ASCII value and XOR it with the checksum:

test = [
    '<L1><PA><IB><MA><WC><OM>Test!',
    '<L1><PA><IB><MA><WC><OM>Testa!',
    '<L1><PA><IB><MA><WC><OM>Test some more',
    '<L1><PA><IE><MA><WC><OE> ',
]


for (let str of test) {
    let cs = 0;
    for (let char of str)
        cs ^= char.charCodeAt(0)
    console.log(str, cs.toString(16))
}

If you like the "functional" style, you can write the inner loop as

let cs = [...str].map(a => a.charCodeAt(0)).reduce((a, b) => a ^ b);