Skip to content

Commit 042ab62

Browse files
authored
Fix serious issue in .toString(16) (#295)
* Add test for `.toString(16)` * Fix serious issue in `.toString(16)` The hex encoding of some numbers is wrong. Since the string representation is also used for interoperability between BigInt libraries, this bug is causing a number modification when a BN.js number is converted into another BigInt class, for example the BigNumber of ethers.js.
1 parent db57519 commit 042ab62

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

lib/bn.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -480,16 +480,16 @@
480480
var w = this.words[i];
481481
var word = (((w << off) | carry) & 0xffffff).toString(16);
482482
carry = (w >>> (24 - off)) & 0xffffff;
483-
if (carry !== 0 || i !== this.length - 1) {
484-
out = zeros[6 - word.length] + word + out;
485-
} else {
486-
out = word + out;
487-
}
488483
off += 2;
489484
if (off >= 26) {
490485
off -= 26;
491486
i--;
492487
}
488+
if (carry !== 0 || i !== this.length - 1) {
489+
out = zeros[6 - word.length] + word + out;
490+
} else {
491+
out = word + out;
492+
}
493493
}
494494
if (carry !== 0) {
495495
out = carry.toString(16) + out;

test/utils-test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@ var BN = require('../').BN;
55

66
describe('BN.js/Utils', function () {
77
describe('.toString()', function () {
8+
describe('hex no padding', function () {
9+
it('should have same length as input', function () {
10+
var hex = '1';
11+
for (var i = 1; i <= 128; i++) {
12+
var n = new BN(hex, 16);
13+
assert.equal(n.toString(16).length, i);
14+
hex = hex + '0';
15+
}
16+
});
17+
});
818
describe('binary padding', function () {
919
it('should have a length of 256', function () {
1020
var a = new BN(0);

0 commit comments

Comments
 (0)