AllYourBase.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * By adding type hints and enabling strict type checking, code can become
  4. * easier to read, self-documenting and reduce the number of potential bugs.
  5. * By default, type declarations are non-strict, which means they will attempt
  6. * to change the original type to match the type specified by the
  7. * type-declaration.
  8. *
  9. * In other words, if you pass a string to a function requiring a float,
  10. * it will attempt to convert the string value to a float.
  11. *
  12. * To enable strict mode, a single declare directive must be placed at the top
  13. * of the file.
  14. * This means that the strictness of typing is configured on a per-file basis.
  15. * This directive not only affects the type declarations of parameters, but also
  16. * a function's return type.
  17. *
  18. * For more info review the Concept on strict type checking in the PHP track
  19. * <link>.
  20. *
  21. * To disable strict typing, comment out the directive below.
  22. */
  23. declare(strict_types=1);
  24. const ErrInBase = "input base must be >= 2";
  25. const ErrOutBase = "output base must be >= 2";
  26. const ErrDigits = "all digits must satisfy 0 <= d < input base";
  27. function rebase(int $fromBase, array $digits, int $toBase): array {
  28. if ($fromBase < 2) {
  29. throw new \InvalidArgumentException(ErrInBase);
  30. }
  31. if ($toBase < 2) {
  32. throw new \InvalidArgumentException(ErrOutBase);
  33. }
  34. if ($fromBase === $toBase) {
  35. return $digits;
  36. }
  37. $rev = array_reverse($digits);
  38. $value = 0;
  39. $pow = 1;
  40. foreach ($rev as $digit) {
  41. if ($digit < 0 || $digit >= $fromBase) {
  42. throw new \InvalidArgumentException(ErrDigits);
  43. }
  44. $value += $digit * $pow;
  45. $pow *= $fromBase;
  46. }
  47. $reversed = [];
  48. $current = $value;
  49. while (TRUE) {
  50. $reversed[] = $current % $toBase;
  51. $current = (int) ($current / $toBase);
  52. if ($current === 0) {
  53. break;
  54. }
  55. }
  56. $out = array_reverse($reversed);
  57. return $out;
  58. }