Skip to content

Commit 6749d81

Browse files
committed
fix(integer-base-converter): fix conversion for number of more than 32bits
1 parent 80e46c9 commit 6749d81

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/tools/integer-base-converter/integer-base-converter.model.test.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ describe('integer-base-converter', () => {
1111
expect(convertBase({ value: '10100101', fromBase: 2, toBase: 16 })).toEqual('a5');
1212
expect(convertBase({ value: '192654', fromBase: 10, toBase: 8 })).toEqual('570216');
1313
expect(convertBase({ value: 'zz', fromBase: 64, toBase: 10 })).toEqual('2275');
14+
expect(convertBase({ value: '42540766411283223938465490632011909384', fromBase: 10, toBase: 10 })).toEqual('42540766411283223938465490632011909384');
15+
expect(convertBase({ value: '42540766411283223938465490632011909384', fromBase: 10, toBase: 16 })).toEqual('20010db8000085a300000000ac1f8908');
16+
expect(convertBase({ value: '20010db8000085a300000000ac1f8908', fromBase: 16, toBase: 10 })).toEqual('42540766411283223938465490632011909384');
1417
});
1518
});
1619
});

src/tools/integer-base-converter/integer-base-converter.model.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@ export function convertBase({ value, fromBase, toBase }: { value: string; fromBa
55
let decValue = value
66
.split('')
77
.reverse()
8-
.reduce((carry: number, digit: string, index: number) => {
8+
.reduce((carry: bigint, digit: string, index: number) => {
99
if (!fromRange.includes(digit)) {
1010
throw new Error(`Invalid digit "${digit}" for base ${fromBase}.`);
1111
}
12-
return (carry += fromRange.indexOf(digit) * fromBase ** index);
13-
}, 0);
12+
return (carry += BigInt(fromRange.indexOf(digit)) * BigInt(fromBase) ** BigInt(index));
13+
}, 0n);
1414
let newValue = '';
1515
while (decValue > 0) {
16-
newValue = toRange[decValue % toBase] + newValue;
17-
decValue = (decValue - (decValue % toBase)) / toBase;
16+
newValue = toRange[Number(decValue % BigInt(toBase))] + newValue;
17+
decValue = (decValue - (decValue % BigInt(toBase))) / BigInt(toBase);
1818
}
1919
return newValue || '0';
2020
}

0 commit comments

Comments
 (0)