1

My client's PHP web application imports CSV data from a 3rd party, and I've been tasked with validating the incoming data by using a checksum to perform a parity check on each line of CSV data. An example line from the 3rd party CSV looks like this:

7450122,8267632,13042013,AP130413-044024,JD012038742880009933,41

The last value on the line is a one-byte Hex checksum sent from the 3rd party against which I need to validate the previous characters using an XOR parity check. The algorithm, as specified by the third party, is:

XOR all data in the record, character by character, truncating to one byte. XORing checksum causes the sum to be zero. Do not include commas or newline characters.

I realize this is textbook CS 101 but I'm just not sure how to implement the algorithm in code, even though I do understand XOR, and what we're trying to accomplish here. The application validating this data is written with PHP but an implementation in any similar language would be tremendously helpful.

njyunis
  • 261
  • 1
  • 3
  • 9

1 Answers1

0

Basically:

$str = '7450......933';
$val = substr($str, 0, 1);
for($i = 2; $i < strlen($var); $i++) {
   $char = substr($str, $i, 1);
   $val ^= $char;
}

This will blindly do the whole string, including that checksum var. So you'll have to add some basic "is it a comma" type logic and skip over the undesirable data. It's not clear if you xor in the checksum value as well.

Marc B
  • 356,200
  • 43
  • 426
  • 500