123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- export function convert(
- digits: number[],
- inputBase: number,
- outputBase: number
- ): number[] {
- if (inputBase < 2) {
- throw new Error("Wrong input base")
- }
- if (outputBase < 2) {
- throw new Error("Wrong output base")
- }
- if (outputBase !== Math.floor(outputBase)) {
- throw new Error("Wrong output base")
- }
- if (inputBase === outputBase) {
- return digits;
- }
- if (digits.length == 0) {
- throw new Error("Input has wrong format");
- }
- if (digits[0] === 0 && digits.length > 1) {
- throw new Error("Input has wrong format");
- }
- let reversed = [...digits];
- reversed.reverse();
- let value = 0;
- let pow = 1;
- for (const digit of reversed) {
- if (digit < 0 || digit >= inputBase) {
- throw new Error("Input has wrong format");
- }
- value += digit * pow;
- pow *= inputBase;
- }
- reversed = [];
- let current = value;
- for (; ;) {
- reversed.push(current % outputBase);
- current = Math.floor(current / outputBase);
- if (current === 0) {
- break;
- }
- }
- const out = [...reversed];
- out.reverse();
- return out;
- }
|