Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function toDecimal($base, $value)
- {
- $value = (string) $value;
- $key = array_flip(str_split($base));
- $base = count($key);
- $parts = str_split($value);
- $steps = count($parts);
- $total = 0;
- for ($i = 0; $i < $steps; $i++)
- {
- $character = $parts[$i];
- $value = $key[$parts[$i]];
- $power = $steps - ($i + 1);
- $net = (int) $value * pow($base, $power);
- $total += $net;
- }
- return $total;
- }
- function fromDecimal($base, $value)
- {
- $points = [];
- $values = [];
- $value = (string) $value;
- $numeric = (int) $value;
- $parts = str_split($base);
- for ($i = 0; $i < 100; $i++)
- {
- array_unshift($points, pow(strlen($base), $i));
- }
- for ($i = 0; $i < 100; $i++)
- {
- $values[] = floor((float) bcdiv(sprintf("%.0f", $numeric), sprintf("%.0f", $points[$i])));
- $numeric = (float) bcmod(sprintf("%.0f", $numeric), sprintf("%.0f", $points[$i]));
- }
- $values = array_map(function($value) use ($parts)
- {
- return $parts[$value];
- }, $values);
- return trim(join("", $values), $parts[0]);
- }
- // $base = " abcdefghijklmnopqrstuvwxyz";
- // $value = "hello world";
- // echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
- // echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
- // $base = "01";
- // $value = "10111001";
- // echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
- // echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
- // $base = "0123456789";
- // $value = "1337";
- // echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
- // echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
- $base = "9876543210";
- $value = "106212424";
- echo "toDecimal: '" . toDecimal($base, $value) . "'\n";
- echo "fromDecimal: '" . fromDecimal($base, toDecimal($base, $value)) . "'\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement