all-your-base.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. export function convert(
  2. digits: number[],
  3. inputBase: number,
  4. outputBase: number
  5. ): number[] {
  6. if (inputBase < 2) {
  7. throw new Error("Wrong input base")
  8. }
  9. if (outputBase < 2) {
  10. throw new Error("Wrong output base")
  11. }
  12. if (outputBase !== Math.floor(outputBase)) {
  13. throw new Error("Wrong output base")
  14. }
  15. if (inputBase === outputBase) {
  16. return digits;
  17. }
  18. if (digits.length == 0) {
  19. throw new Error("Input has wrong format");
  20. }
  21. if (digits[0] === 0 && digits.length > 1) {
  22. throw new Error("Input has wrong format");
  23. }
  24. let reversed = [...digits];
  25. reversed.reverse();
  26. let value = 0;
  27. let pow = 1;
  28. for (const digit of reversed) {
  29. if (digit < 0 || digit >= inputBase) {
  30. throw new Error("Input has wrong format");
  31. }
  32. value += digit * pow;
  33. pow *= inputBase;
  34. }
  35. reversed = [];
  36. let current = value;
  37. for (; ;) {
  38. reversed.push(current % outputBase);
  39. current = Math.floor(current / outputBase);
  40. if (current === 0) {
  41. break;
  42. }
  43. }
  44. const out = [...reversed];
  45. out.reverse();
  46. return out;
  47. }