title: How to implement a Longitudinal Redundancy Check (LRC/CRC8/XOR8) checksum in PHP?
body: <p>I'm having real problems trying to implement a XOR8/LRC checksum in PHP, according to the algorithm present here: <a href="http://en.wikipedia.org/wiki/Longitudinal_redundancy_check" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Longitudinal_redundancy_check</a></p>
  
  <p>What I'm trying to do is, given any string calculate its LRC checksum.</p>
  
  <p>For example, I know for sure this string:</p>
  
  <pre><code>D$1I 11/14/2006 18:15:00 1634146 3772376 3772344 3772312 3772294 1*
  </code></pre>
  
  <p>Has a hexadecimal checksum of 39 (including the last <code>*</code> char).</p>
  
  <p>For anyone interested what is the meaning of the string, it's is a DART (Deep-ocean Assesment and Reporting of Tsunamis) message  - <a href="http://nctr.pmel.noaa.gov/Dart/Pdf/dartMsgManual3.01.pdf" rel="nofollow noreferrer">http://nctr.pmel.noaa.gov/Dart/Pdf/dartMsgManual3.01.pdf</a>.</p>
  
  <p>I convert the string to a binary string with 1's and 0's. From there, I try to create a byte array and apply the algorithm to the byte array, but it's not working and I can't figure out why.</p>
  
  <p>The function I'm using for converting to String to Binary String is:</p>
  
  <pre><code>        function str2binStr($str) { 
           $ret = '';
           for ($i = 0, $n = strlen($str); $i &lt; $n; ++$i) 
             $ret .= str_pad(decbin(ord($str[$i])), 8, 0, STR_PAD_LEFT); 
           return $ret; 
          }
  </code></pre>
  
  <p>The function I'm using for converting from Binary String to Binary Array is:</p>
  
  <pre><code>        function byteStr2byteArray($s) {
            return array_slice(unpack("C*", "\0".$s), 1);
          }
  </code></pre>
  
  <p>Finally, the LRC implementation I'm using, with bitwise operators, is:</p>
  
  <pre><code>        function lrc($byteArr) {
             $lrc = 0;
             $byteArrLen = count($byteArr);
             for ($i = 0; $i &lt; $byteArrLen; $i++) {
               $lrc = ($lrc + $byteArr[$i]) &amp; 0xFF;
             }
             $lrc = (($lrc ^ 0xFF) + 1) &amp; 0xFF;
             return $lrc;
          }
  </code></pre>
  
  <p>Then, we convert the final decimal result of the LRC checksum with dechex($checksum + 0), so we have the final hexadecimal checksum.</p>
  
  <p>After all these operations, I'm not getting the expected result, so <strong>any help will be highly appreciated</strong>.</p>
  
  <p>Thanks in advance.</p>
  
  <hr>
  
  <p>Also, I can't make it work following the <a href="https://stackoverflow.com/questions/507041/crc8-check-in-php">CRC8-Check in PHP</a> answer.</p>