Skip to content

Instantly share code, notes, and snippets.

@jgrossi
Created November 11, 2014 22:18
Show Gist options
  • Save jgrossi/a4eb21bbe00763d63385 to your computer and use it in GitHub Desktop.
Save jgrossi/a4eb21bbe00763d63385 to your computer and use it in GitHub Desktop.
Math class from Taylor Otwell. Thanks to @brad ([email protected]) 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;
}
}
@chasen
Copy link

chasen commented Jan 30, 2017

The PHPDoc block for @param int $base should be updated to match the method functions: @param int $b. Otherwise, thanks for this very useful!

@jeremyikwuje
Copy link

jeremyikwuje commented May 27, 2018

Thanks for this. I found out that this class can generate some negative word like sex. Please remove all vowels from the $base.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment