Skip to content

Commit

Permalink
Added buffer variants for crc 8/16/32
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Apr 27, 2012
1 parent 9c78fae commit 830159d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
31 changes: 30 additions & 1 deletion lib/crc.js
Expand Up @@ -253,6 +253,14 @@
return crc;
};

function crc8Buffer(buf) {
var crc = 0;
for (var i = 0, len = buf.length; i < len; ++i) {
crc = crc8Add(crc, buf[i]);
}
return crc;
}

function crcArc(str)
{
var i,
Expand All @@ -279,6 +287,14 @@
return crc;
};

function crc16Buffer(buf) {
var crc = 0;
for (var i = 0, len = buf.length; i < len; ++i) {
crc = crc16Add(crc, buf[i]);
}
return crc;
}

function fcs16(str)
{
var i,
Expand All @@ -305,6 +321,14 @@
return crc^0xFFFFFFFF;
};

function crc32Buffer(buf) {
var crc = 0xFFFFFFFF;
for (var i = 0, len = buf.length; i < len; ++i) {
crc = crc32Add(crc, buf[i]);
}
return crc ^ 0xFFFFFFFF;
}

/**
* Convert value as 8-bit unsigned integer to 2 digit hexadecimal number.
*/
Expand Down Expand Up @@ -357,6 +381,11 @@
'crc32' : crc32,
'hex8' : hex8,
'hex16' : hex16,
'hex32' : hex32
'hex32' : hex32,
'buffer' : {
crc8: crc8Buffer,
crc16: crc16Buffer,
crc32: crc32Buffer
}
};
})();
12 changes: 12 additions & 0 deletions test/crc.js
Expand Up @@ -6,18 +6,30 @@ describe('crc8()', function(){
it('should work with strings', function(){
crc.crc8('hello world').should.equal(64);
})

it('should work with Buffers', function(){
crc.buffer.crc8(new Buffer('hello world')).should.equal(64);
})
})

describe('crc16()', function(){
it('should work with strings', function(){
crc.crc16('hello world').should.equal(15332);
})

it('should work with Buffers', function(){
crc.buffer.crc16(new Buffer('hello world')).should.equal(15332);
})
})

describe('crc32()', function(){
it('should work with strings', function(){
crc.crc32('hello world').should.equal(222957957);
})

it('should work with Buffers', function(){
crc.buffer.crc32(new Buffer('hello world')).should.equal(222957957);
})
})

describe('crcArc()', function(){
Expand Down

0 comments on commit 830159d

Please sign in to comment.