Skip to content

Instantly share code, notes, and snippets.

@nczz
Forked from jgrossi/Math.php
Created February 20, 2018 14:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nczz/09f4afcfecf4737f552de663cb8ceba7 to your computer and use it in GitHub Desktop.
Save nczz/09f4afcfecf4737f552de663cb8ceba7 to your computer and use it in GitHub Desktop.
Math class from Taylor Otwell. Thanks to @brad (captain_jim1@yahoo.com) for the class content.
<?php
class Math {
/**
* The base.
*
* @var string
*/
private static $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* Convert a from a given base to base 10.
*
* @param string $value
* @param int $base
* @return int
*/
public static function to_base_10($value, $b = 62)
{
$limit = strlen($value);
$result = strpos(static::$base, $value[0]);
for($i = 1; $i < $limit; $i++)
{
$result = $b * $result + strpos(static::$base, $value[$i]);
}
return $result;
}
/**
* Convert from base 10 to another base.
*
* @param int $value
* @param int $base
* @return string
*/
public static function to_base($value, $b = 62)
{
$r = $value % $b;
$result = static::$base[$r];
$q = floor($value / $b);
while ($q)
{
$r = $q % $b;
$q = floor($q / $b);
$result = static::$base[$r].$result;
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment