Advertisement
Guest User

Untitled

a guest
Aug 30th, 2015
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. <?php
  2.  
  3. function toDecimal($base, $value)
  4. {
  5. $value = (string) $value;
  6.  
  7. $key = array_flip(str_split($base));
  8. $base = count($key);
  9.  
  10. $parts = str_split($value);
  11. $steps = count($parts);
  12. $total = 0;
  13.  
  14. for ($i = 0; $i < $steps; $i++)
  15. {
  16. $character = $parts[$i];
  17. $value = $key[$parts[$i]];
  18. $power = $steps - ($i + 1);
  19. $net = (int) $value * pow($base, $power);
  20.  
  21. $total += $net;
  22. }
  23.  
  24. return $total;
  25. }
  26.  
  27. function fromDecimal($base, $value)
  28. {
  29. $points = [];
  30. $values = [];
  31. $value = (string) $value;
  32. $numeric = (int) $value;
  33. $parts = str_split($base);
  34.  
  35. for ($i = 0; $i < 100; $i++)
  36. {
  37. array_unshift($points, pow(strlen($base), $i));
  38. }
  39.  
  40. for ($i = 0; $i < 100; $i++)
  41. {
  42. $values[] = floor((float) bcdiv(sprintf("%.0f", $numeric), sprintf("%.0f", $points[$i])));
  43. $numeric = (float) bcmod(sprintf("%.0f", $numeric), sprintf("%.0f", $points[$i]));
  44. }
  45.  
  46. $values = array_map(function($value) use ($parts)
  47. {
  48. return $parts[$value];
  49.  
  50. }, $values);
  51.  
  52. return trim(join("", $values), $parts[0]);
  53. }
  54.  
  55. // $base = " abcdefghijklmnopqrstuvwxyz";
  56. // $value = "hello world";
  57.  
  58. // echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
  59. // echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
  60.  
  61. // $base = "01";
  62. // $value = "10111001";
  63.  
  64. // echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
  65. // echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
  66.  
  67. // $base = "0123456789";
  68. // $value = "1337";
  69.  
  70. // echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
  71. // echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
  72.  
  73. $base = "9876543210";
  74. $value = "106212424";
  75.  
  76. echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
  77. echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement