Skip to content

Commit

Permalink
[crc32] ensure results are always unsigned
Browse files Browse the repository at this point in the history
With longer inputs, previous crc-32 can give signed (negative) results,
which are incorrect. This patch shifts the result right-wise, filling in
the left with zeros, to ensure the result is unsigned (unlike the C++
implementation, JS lacks a standard unsigned type).

I used OS X's "cksum -o3" command to get the expected CRC-32 output for
the test file.
  • Loading branch information
alunny committed Sep 14, 2012
1 parent b21d53b commit 8c8aa27
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/crc.js
Expand Up @@ -326,7 +326,7 @@
for(i = 0; i < len; i++)
crc = crc32Add(crc, str.charCodeAt(i));

return crc^0xFFFFFFFF;
return (crc^0xFFFFFFFF) >>> 0;
};

function crc32Buffer(buf)
Expand All @@ -338,7 +338,7 @@
crc = crc32Add(crc, buf[i]);
}

return crc ^ 0xFFFFFFFF;
return (crc ^ 0xFFFFFFFF) >>> 0;
}

/**
Expand Down
18 changes: 17 additions & 1 deletion test/crc.js
@@ -1,6 +1,8 @@
#!/usr/bin/env ./nodeunit/bin/nodeunit

var crc = require('../lib/crc');
var crc = require('../lib/crc'),
fs = require('fs'),
format = require('util').format;

describe('crc8()', function(){
it('should work with strings', function(){
Expand All @@ -27,9 +29,23 @@ describe('crc32()', function(){
crc.crc32('hello world').should.equal(222957957);
})

it('should work with bigger strings', function(){
var path = format("%s/index.html", __dirname),
fileContents = fs.readFileSync(path, 'utf-8');

crc.crc32(fileContents).should.equal(3026001449);
});

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

it('should work with bigger Buffers', function(){
var path = format("%s/index.html", __dirname),
fileContents = fs.readFileSync(path);

crc.buffer.crc32(fileContents).should.equal(3026001449);
});
})

describe('crcArc()', function(){
Expand Down
18 changes: 18 additions & 0 deletions test/index.html
@@ -0,0 +1,18 @@
<html>
<head></head>
<body>
<h1>Child Browser Demo</h1>

<a onClick="launchBrowser()" href="#">What does it do?</a>

</body>
<script src="phonegap.js"></script>
<script src="childbrowser.js"></script>
<script>
var url = 'http://www.youtube.com/watch?v=R4vpXS5BKyc'
function launchBrowser() {
window.plugins.childBrowser.showWebPage(url,
{ showLocationBar: true });
}
</script>
</html>

0 comments on commit 8c8aa27

Please sign in to comment.