首页 > 编程语言 > 详细

Crc8算法

时间:2020-12-04 11:51:01      阅读:188      评论:0      收藏:0      [点我收藏+]

JavaScript实现:

https://gitee.com/tgzhome/crc8js

// "Class" for calculating CRC8 checksums...
function CRC8(polynomial, initial_value) { // constructor takes an optional polynomial type from CRC8.POLY
  if (polynomial == null) polynomial = CRC8.POLY.CRC8_CCITT
  this.table = CRC8.generateTable(polynomial);
  this.initial_value = initial_value;
}

// Returns the 8-bit checksum given an array of byte-sized numbers
CRC8.prototype.checksum = function(byte_array) {
  var c = this.initial_value;

  for (var i = 0; i < byte_array.length; i++ ) 
    c = this.table[(c ^ byte_array[i]) % 256] 

  return c;
} 

// returns a lookup table byte array given one of the values from CRC8.POLY 
CRC8.generateTable =function(polynomial)
{
  var csTable = [] // 256 max len byte array
  
  for ( var i = 0; i < 256; ++i ) {
    var curr = i
    for ( var j = 0; j < 8; ++j ) {
      if ((curr & 0x80) !== 0) {
        curr = ((curr << 1) ^ polynomial) % 256
      } else {
        curr = (curr << 1) % 256
      }
    }
    csTable[i] = curr 
  }
    
  return csTable
}

// This "enum" can be used to indicate what kind of CRC8 checksum you will be calculating
CRC8.POLY = {
  CRC8 : 0xd5,
  CRC8_CCITT : 0x07,
  CRC8_DALLAS_MAXIM : 0x31,
  CRC8_SAE_J1850 : 0x1D,
  CRC_8_WCDMA : 0x9b,
}
var crc8 = new CRC8();
module.exports = crc8;

  

 

Crc8算法

原文:https://www.cnblogs.com/tgzmos/p/14084253.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!