Skip to content

Commit

Permalink
Merge pull request #20 from lajonat/master
Browse files Browse the repository at this point in the history
Encode int64 numbers
  • Loading branch information
mcollina committed May 6, 2015
2 parents 2d49f07 + 4d3c647 commit 161d7c4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
8 changes: 6 additions & 2 deletions lib/decoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,9 @@ module.exports = function buildDecode(decodingTypes) {

var first = buf.readUInt8(offset)
, length
, result
, result = 0
, type
, bytePos

if (!hasMinBufferSize(first, bufLength)) {
return null
Expand All @@ -142,7 +143,10 @@ module.exports = function buildDecode(decodingTypes) {
return buildDecodeResult(result, 5)
case 0xcf:
// 8-bytes BE unsigned int
result = buf.readUInt32BE(offset + 5) * 0xffffffff + buf.readUInt32BE(offset + 1)
// Read long byte by byte, big-endian
for (bytePos = 7; bytePos >= 0; bytePos--) {
result += (buf.readUInt8(offset + bytePos + 1) * Math.pow(2 , (8 *(7-bytePos))));
}
return buildDecodeResult(result, 9)
case 0xd0:
// 1-byte signed int
Expand Down
8 changes: 5 additions & 3 deletions lib/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,11 @@ module.exports = function buildEncode(encodingTypes) {
}

function write64BitUint(buf, obj) {
var big = Math.floor(obj / 0xffffffff)
buf.writeUInt32BE(big, 5)
buf.writeUInt32BE(obj - big * 0xffffffff, 1)
// Write long byte by byte, in big-endian order
for (var currByte = 7; currByte >= 0; currByte--) {
buf[currByte + 1] = (obj & 0xff);
obj = obj / 256;
}
}

function isFloat(n) {
Expand Down
6 changes: 5 additions & 1 deletion test/64-bits-unsigned-integers.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ test('encoding/decoding 64-bits big-endian unsigned integers', function(t) {
var buf = encoder.encode(num)
t.equal(buf.length, 9, 'must have 9 bytes')
t.equal(buf[0], 0xcf, 'must have the proper header')
t.equal(buf.readUInt32BE(5) * base + buf.readUInt32BE(1), num, 'must decode correctly');
var result = 0;
for (var k = 7; k >= 0; k--) {
result += (buf.readUInt8(k + 1) * Math.pow(2 , (8 *(7-k))));
}
t.equal(result, num, 'must decode correctly');
t.end()
})

Expand Down

0 comments on commit 161d7c4

Please sign in to comment.