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: number, digit: string, index: number) => {
|
|
|
|
if (!fromRange.includes(digit)) {
|
2022-12-07 21:52:24 +01:00
|
|
|
throw new Error('Invalid digit "' + digit + '" for base ' + fromBase + '.');
|
2022-04-12 14:27:52 +02:00
|
|
|
}
|
|
|
|
return (carry += fromRange.indexOf(digit) * Math.pow(fromBase, index));
|
|
|
|
}, 0);
|
|
|
|
let newValue = '';
|
|
|
|
while (decValue > 0) {
|
|
|
|
newValue = toRange[decValue % toBase] + newValue;
|
|
|
|
decValue = (decValue - (decValue % toBase)) / toBase;
|
|
|
|
}
|
|
|
|
return newValue || '0';
|
|
|
|
}
|