Skip to content

Commit

Permalink
toBuffer() tests finally pass
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Feb 22, 2011
1 parent 3bcb089 commit ca4f45e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 14 deletions.
12 changes: 7 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,17 +313,19 @@ BigInt.prototype.toBuffer = function (opts) {
'converting negative numbers to Buffers not supported yet'
);

var hx = ((hex.length % 2 === 1 ? '0' : '') + hex)
var len = Math.ceil(hex.length / (2 * size)) * size;
var buf = new Buffer(len);

// zero-pad the hex string so the chunks are all `size` long
while (hex.length < 2 * len) hex = '0' + hex;

var hx = hex
.split(new RegExp('(.{' + (2 * size) + '})'))
.filter(function (s) { return s.length > 0 })
;

var len = Math.ceil(hex.length / (2 * size)) * size;
var buf = new Buffer(len);
(order === 'forward' ? hx : hx.reverse())
.forEach(function (chunk, i) {
while (chunk.length < size * 2) { chunk = chunk + '00' }

for (var j = 0; j < size; j++) {
var ix = i * size + (endian === 'big' ? j : size - j - 1);
buf[ix] = parseInt(chunk.slice(j*2,j*2+2), 16);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name" : "bigint",
"version" : "0.0.7",
"version" : "0.0.8",
"description" : "Arbitrary-precision integer arithmetic using libgmp",
"main" : "./index.js",
"repository" : {
Expand Down
12 changes: 4 additions & 8 deletions test/buf.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ exports.toBuf = function () {
[].slice.call(bigint(43135012110).toBuffer({
endian : 'little', size : 4
})),
[ 0x00, 0x00, 0x00, 0x0a, 0x0e, 0x0d, 0x0c, 0x0b ]
[ 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b ]
);

assert.eql(
Expand All @@ -158,16 +158,12 @@ exports.zeroPad = function () {
var b = bigint(0x123456);

assert.eql(
[].slice.call(
b.toBuffer({ endian : 'big', size:4 })
),
[].slice.call(b.toBuffer({ endian : 'big', size:4 })),
[ 0x00, 0x12, 0x34, 0x56 ]
);

assert.eql(
[].slice.call(
b.toBuffer({ endian : 'little', size:4 })
),
[ 0x00, 0x56, 0x34, 0x12 ]
[].slice.call(b.toBuffer({ endian : 'little', size:4 })),
[ 0x56, 0x34, 0x12, 0x00 ]
);
};

0 comments on commit ca4f45e

Please sign in to comment.