Skip to content

Instantly share code, notes, and snippets.

@assertchris
Last active June 6, 2016 00:18
Show Gist options
  • Select an option

  • Save assertchris/5097745 to your computer and use it in GitHub Desktop.

Select an option

Save assertchris/5097745 to your computer and use it in GitHub Desktop.
Converting from any base number system to decimal (and back).
<?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";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment