CRC计算超过26个字节

时间:2015-08-03 07:14:36

标签: javascript node.js crc

我实现简单的协议,我需要从以下结构计算CRC:

type    (1 byte, unsigned)
address (1 byte, unsigned)
dataID  (4 bytes, unsigned, little-endian)
data    (4 bytes, unsigned, little-endian)
data    (4 bytes, unsigned, little-endian)
data    (4 bytes, unsigned, little-endian)
data    (4 bytes, unsigned, little-endian)
data    (4 bytes, unsigned, little-endian)
-----------------
=       (26 bytes)

您可以将其想象为简单的JavaScript对象:

var message = {
  type:    0x11,
  address: 0x01,
  dataID:  0xFFFFFFFF,
  data: [
    0xFFFFFFFF,
    0xFFFFFFFF,
    0xFFFFFFFF,
    0xFFFFFFFF,
    0xFFFFFFFF
  ]
}

从这个对象我需要计算CRC。不幸的是,在手册中仅CRC calculation includes Message type, Slave Address Data-ID's and data values. CRC calculation is performed over 26 bytes.,所以我不确定该怎么做。

使用CRC16-CCIT函数计算CRC。所以我从NPM下载了crc package,它已经实现了这个功能。

如果你发给我代码会很棒,因为我不知道该怎么做(你可以使用相当于this的未声明的crc函数。)

1 个答案:

答案 0 :(得分:1)

你可以从这开始:

var crc16ccitt = require('crc').crc16ccitt;

function checksum(message) {
  var buf = new Buffer(26);
  buf.writeUInt8(message.type,      0);
  buf.writeUInt8(message.address,   1);
  buf.writeUInt32LE(message.dataID, 2);
  for (var i = 0; i < 5; i++) {
    buf.writeUInt32LE(message.data[i], 6 + i * 4);
  }
  return crc16ccitt(buf);
}