Permalink
Browse files

Adding support for crc-ccitt

CCITT is very similar to the existing crc16 functions, except that the
initial value is set to 0xFFFF. Test values were verified using pycrc,
and other test strings were verified from developer documentation for
the ReefNet Sensus device I'm working with (though not included in
test/crc.js).
  • Loading branch information...
1 parent b21d53b commit 776779119992ef89f48e7385efb2a1ffcf3871fe @underbluewaters underbluewaters committed May 27, 2012
Showing with 57 additions and 20 deletions.
  1. +9 −8 README.md
  2. +39 −12 lib/crc.js
  3. +9 −0 test/crc.js
View
@@ -8,14 +8,15 @@ Original code is taken from http://www.digsys.se/JavaScript/CRC.aspx
The following functions are implemented:
- crc8(String) #=> Number
- crcArc(String) #=> Number
- crc16(String) #=> Number
- fcs16(String) #=> Number
- crc32(String) #=> Number
- hex8(Number) #=> String
- hex16(Number) #=> String
- hex32(Number) #=> String
+ crc8(String) #=> Number
+ crcArc(String) #=> Number
+ crc16(String) #=> Number
+ crc16CCITT(String) #=> Number
+ fcs16(String) #=> Number
+ crc32(String) #=> Number
+ hex8(Number) #=> String
+ hex16(Number) #=> String
+ hex32(Number) #=> String
## Installation
View
@@ -303,6 +303,31 @@
return crc;
}
+ function crc16CCITT(str)
+ {
+ var i,
+ len = str.length,
+ crc = 0xFFFF
+ ;
+
+ for(i = 0; i < len; i++)
+ crc = crc16Add(crc, str.charCodeAt(i));
+
+ return crc^0x0000;
+ };
+
+ function crc16CCITTBuffer(buf)
+ {
+ var crc = 0xFFFF;
+
+ for (var i = 0, len = buf.length; i < len; ++i)
+ {
+ crc = crc16Add(crc, buf[i]);
+ }
+
+ return crc^0x0000;
+ }
+
function fcs16(str)
{
var i,
@@ -386,18 +411,20 @@
}
target[property] = {
- 'crc8' : crc8,
- 'crcArc' : crcArc,
- 'crc16' : crc16,
- 'fcs16' : fcs16,
- 'crc32' : crc32,
- 'hex8' : hex8,
- 'hex16' : hex16,
- 'hex32' : hex32,
- 'buffer' : {
- crc8 : crc8Buffer,
- crc16 : crc16Buffer,
- crc32 : crc32Buffer
+ 'crc8' : crc8,
+ 'crcArc' : crcArc,
+ 'crc16' : crc16,
+ 'crc16CCITT' : crc16CCITT,
+ 'fcs16' : fcs16,
+ 'crc32' : crc32,
+ 'hex8' : hex8,
+ 'hex16' : hex16,
+ 'hex32' : hex32,
+ 'buffer' : {
+ crc8 : crc8Buffer,
+ crc16 : crc16Buffer,
+ crc16CCITT : crc16CCITTBuffer,
+ crc32 : crc32Buffer
}
};
})();
View
@@ -61,3 +61,12 @@ describe('hex32()', function(){
crc.hex32(222957957).should.equal('0D4A1185');
})
})
+
+describe('crc16CCITT()', function(){
+ it('should work with strings', function(){
+ crc.crc16CCITT('hello world').should.equal(61419);
+ })
+ it('should work with buffers', function(){
+ crc.buffer.crc16CCITT(new Buffer('hello world')).should.equal(61419);
+ })
+})

0 comments on commit 7767791

Please sign in to comment.