1 頁 (共 1 頁)

LRC 校驗 縱向冗餘檢查 PHP版

發表於 : 2012-05-09 11:13:22
yehlu
Longitudinal redundancy check

1.LRC是checksum用.應是針對(Data[]+ETX)作XOR的結果.

代碼: 選擇全部

Data=Data[0];
for ( i=1; i < length; i++ ) Data = Data xor Data[i];
LRC=Data xor ETX;
2.在將 (header data if need)+ Data[]+ETX+LRC +(tail data if need) 送到前端設備.

因 PHP 為自動型態,故要特別轉換型態後,再計算

代碼: 選擇全部

function lrc($buffer){
    foreach (str_split($buffer, 1) as $b)
    {
        $byteArr[] = $b;
    }         
    $data = $byteArr[0];
    for ($i = 1; $i < count($byteArr); $i++) {           
        $data = chr(ord($data) ^ ord($byteArr[$i]));         
    }                
    $lrc = ord($data) ^ 0x3;                       
    return dechex($lrc);           
}

Re: LRC 校驗 縱向冗餘檢查 PHP版

發表於 : 2016-03-20 15:53:58
yehlu
https://github.com/alohasteveb/lrc-php

代碼: 選擇全部

<?php

namespace AlohaSteve;

/**
* Implementation of Longitudinal Redundancy Check.
*
* @author Steve Be
* @version 0.1.0
*
*/

class Lrc {
  private $endSymbol = NULL;

/**
* @param string $symbol A 1-byte or 1-character end symbol. Use a single-byte character set.
* @throws \LrcConfigurationException If parameter is not a single character/byte
*/
  public function setEndSymbol($symbol = NULL) {
    if (is_null($symbol) || (strlen($symbol) !== 1)) throw new LrcConfigurationException("End symbol must be exactly 1 byte long.");

    $this->endSymbol = $symbol;
  }


  /**
  * @param string $message A non-empty message for which to generate the check byte/character. Use a single-byte character set.
  * @throws \LrcConfigurationException If end symbol is not set or message is empty.
  */

  public function getCheck($message = NULL) {
    if (is_null($this->endSymbol)) throw new LrcConfigurationException("End Symbol must be set to generate a check.");
    if (is_null($message) || (strlen($message) === 0)) throw new LrcConfigurationException("Messages must be at least 1 byte long.");

    $extendedMessage = $message . $this->endSymbol;

    $extendedMessageLength = strlen($extendedMessage);

    $check = substr($extendedMessage, 0, 1);
    for ($i = 1; $i < $extendedMessageLength ; $i++) {
            $check ^= substr($extendedMessage, $i, 1);
    }
    return $check;
  }
}


class LrcException extends \Exception {};
class LrcConfigurationException extends LrcException {};

代碼: 選擇全部

require('Lrc.class.php');

$myLrc = new \AlohaSteve\Lrc();

$myLrc->setEndSymbol($endSymbol);

$extendedMessage = $startSymbol . $baseMessage . $endSymbol . $myLrc->getCheck($baseMessage); //LRC calculation includes termination/ending symbol but not start symbol