Bases

in ita •  16 hours ago 

export function convert(
digits: number[],
inputBase: number,
outputBase: number
): number[] {
let res: number[] = [];
let resNum = 0;
let exp = digits.length-1;
let toAdd = 0;

if (inputBase <=1) throw new Error('Wrong input base');
if (outputBase <=1 || !Number.isInteger(outputBase)) throw new Error('Wrong output base');
if (digits[0] === 0 && digits.length > 1) throw new Error('Input has wrong format');
if (digits.length === 0) throw new Error('Input has wrong format');

for(let j=0; j<digits.length; j++){
if(digits[j]<0) throw new Error('Input has wrong format');
if(digits[j] === inputBase) throw new Error('Input has wrong format');
resNum += Number(digits[j]) * Math.pow(inputBase, exp-j);
}

while(resNum >= outputBase){
toAdd = resNum % outputBase;
resNum = Math.floor(resNum / outputBase);
res.push(toAdd);
}
toAdd = resNum % outputBase;
resNum = Math.floor(resNum / outputBase);
res.push(toAdd);
res.reverse();
return res;
}

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!