mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-04-21 23:36:15 -04:00
fix(integer base converter): support bigint (#872)
This commit is contained in:
parent
23f82d956a
commit
9eac9cb2a9
2 changed files with 8 additions and 5 deletions
|
@ -11,6 +11,9 @@ describe('integer-base-converter', () => {
|
||||||
expect(convertBase({ value: '10100101', fromBase: 2, toBase: 16 })).toEqual('a5');
|
expect(convertBase({ value: '10100101', fromBase: 2, toBase: 16 })).toEqual('a5');
|
||||||
expect(convertBase({ value: '192654', fromBase: 10, toBase: 8 })).toEqual('570216');
|
expect(convertBase({ value: '192654', fromBase: 10, toBase: 8 })).toEqual('570216');
|
||||||
expect(convertBase({ value: 'zz', fromBase: 64, toBase: 10 })).toEqual('2275');
|
expect(convertBase({ value: 'zz', fromBase: 64, toBase: 10 })).toEqual('2275');
|
||||||
|
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');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -5,16 +5,16 @@ export function convertBase({ value, fromBase, toBase }: { value: string; fromBa
|
||||||
let decValue = value
|
let decValue = value
|
||||||
.split('')
|
.split('')
|
||||||
.reverse()
|
.reverse()
|
||||||
.reduce((carry: number, digit: string, index: number) => {
|
.reduce((carry: bigint, digit: string, index: number) => {
|
||||||
if (!fromRange.includes(digit)) {
|
if (!fromRange.includes(digit)) {
|
||||||
throw new Error(`Invalid digit "${digit}" for base ${fromBase}.`);
|
throw new Error(`Invalid digit "${digit}" for base ${fromBase}.`);
|
||||||
}
|
}
|
||||||
return (carry += fromRange.indexOf(digit) * fromBase ** index);
|
return (carry += BigInt(fromRange.indexOf(digit)) * BigInt(fromBase) ** BigInt(index));
|
||||||
}, 0);
|
}, 0n);
|
||||||
let newValue = '';
|
let newValue = '';
|
||||||
while (decValue > 0) {
|
while (decValue > 0) {
|
||||||
newValue = toRange[decValue % toBase] + newValue;
|
newValue = toRange[Number(decValue % BigInt(toBase))] + newValue;
|
||||||
decValue = (decValue - (decValue % toBase)) / toBase;
|
decValue = (decValue - (decValue % BigInt(toBase))) / BigInt(toBase);
|
||||||
}
|
}
|
||||||
return newValue || '0';
|
return newValue || '0';
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue