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

21 lines
861 B
TypeScript
Raw Normal View History

2022-04-12 14:27:52 +02:00
export function convertBase({ value, fromBase, toBase }: { value: string; fromBase: number; toBase: number }) {
const range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
const fromRange = range.slice(0, fromBase);
const toRange = range.slice(0, toBase);
let decValue = value
.split('')
.reverse()
.reduce((carry: bigint, digit: string, index: number) => {
2022-04-12 14:27:52 +02:00
if (!fromRange.includes(digit)) {
throw new Error(`Invalid digit "${digit}" for base ${fromBase}.`);
2022-04-12 14:27:52 +02:00
}
return (carry += BigInt(fromRange.indexOf(digit)) * BigInt(fromBase) ** BigInt(index));
}, 0n);
2022-04-12 14:27:52 +02:00
let newValue = '';
while (decValue > 0) {
newValue = toRange[Number(decValue % BigInt(toBase))] + newValue;
decValue = (decValue - (decValue % BigInt(toBase))) / BigInt(toBase);
2022-04-12 14:27:52 +02:00
}
return newValue || '0';
}