mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-05-05 05:47:10 -04:00
fix(integer-base-converter): fix conversion for number of more than 32bits
This commit is contained in:
parent
e336ebe6bb
commit
34357dde7c
2 changed files with 8 additions and 5 deletions
|
@ -26,6 +26,9 @@ describe('integer-base-converter', () => {
|
|||
expect(convertBase({ value: '0b10101010', fromBase: -1, toBase: 10 })).toEqual('170');
|
||||
expect(convertBase({ value: '0b_1010_1010', fromBase: -1, toBase: 10 })).toEqual('170');
|
||||
expect(convertBase({ value: '192,654', fromBase: 10, toBase: 8 })).toEqual('570216');
|
||||
expect(convertBase({ value: '42540766411283223938465490632011909384', fromBase: 10, toBase: 10 })).toEqual('42540766411283223938465490632011909384');
|
||||
expect(convertBase({ value: '42540766411283223938465490632011909384', fromBase: 10, toBase: 16 })).toEqual('20010db8000085a300000000ac1f8908');
|
||||
expect(convertBase({ value: '20010db8000085a300000000ac1f8908', fromBase: 16, toBase: 10 })).toEqual('42540766411283223938465490632011909384');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -46,16 +46,16 @@ export function convertBase(
|
|||
let decValue = cleanedValue
|
||||
.split('')
|
||||
.reverse()
|
||||
.reduce((carry: number, digit: string, index: number) => {
|
||||
.reduce((carry: bigint, digit: string, index: number) => {
|
||||
if (!fromRange.includes(digit)) {
|
||||
throw new Error(`Invalid digit "${digit}" for base ${finalFromBase}.`);
|
||||
}
|
||||
return (carry += fromRange.indexOf(digit) * finalFromBase ** index);
|
||||
}, 0);
|
||||
return (carry += BigInt(fromRange.indexOf(digit)) * BigInt(finalFromBase) ** BigInt(index));
|
||||
}, 0n);
|
||||
let newValue = '';
|
||||
while (decValue > 0) {
|
||||
newValue = toRange[decValue % toBase] + newValue;
|
||||
decValue = (decValue - (decValue % toBase)) / toBase;
|
||||
newValue = toRange[Number(decValue % BigInt(toBase))] + newValue;
|
||||
decValue = (decValue - (decValue % BigInt(toBase))) / BigInt(toBase);
|
||||
}
|
||||
return newValue || '0';
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue