Skip to content

Instantly share code, notes, and snippets.

@jsjohnst
Created June 9, 2009 23:06
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save jsjohnst/126883 to your computer and use it in GitHub Desktop.
Save jsjohnst/126883 to your computer and use it in GitHub Desktop.
<?php
class base58
{
static public $alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
public static function encode($int) {
$base58_string = "";
$base = strlen(self::$alphabet);
while($int >= $base) {
$div = floor($int / $base);
$mod = ($int - ($base * $div)); // php's % is broke with >32bit int on 32bit proc
$base58_string = self::$alphabet{$mod} . $base58_string;
$int = $div;
}
if($int) $base58_string = self::$alphabet{$int} . $base58_string;
return $base58_string;
}
public static function decode($base58) {
$int_val = 0;
for($i=strlen($base58)-1,$j=1,$base=strlen(self::$alphabet);$i>=0;$i--,$j*=$base) {
$int_val += $j * strpos(self::$alphabet, $base58{$i});
}
return $int_val;
}
}
<?php
include("base58.php");
echo "http://flic.kr/p/" . base58::encode(3392387861) . "\n";
// outputs: http://flic.kr/p/6aLSHT
echo "3392387861 = " . base58::decode(base58::encode(3392387861)) . "\n";
// outputs: 3392387861 = 3392387861
@scottchiefbaker
Copy link

Is there a way to use this with raw binary data, instead of integers?

@josecelano
Copy link

I get this error String offset cast occurred in line:

$base58_string = self::$alphabet{$mod} . $base58_string;

becuase $mod is a float. The error seem to be fixed casting to integer.

@donpdonp
Copy link

donpdonp commented May 26, 2017

I was getting the offset cast warning too. I figure in 2017 the 32bit proc concern was not relevant, so using % and intval() cured those warnings.

<?php
class base58
{
	static public $alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

	public static function encode($int) {
		$base58_string = "";
		$base = strlen(self::$alphabet);
		while($int >= $base) {
			$div = floor($int / $base);
			$mod = $int % $base;
			$base58_string = self::$alphabet{$mod} . $base58_string;
			$int = $div;
		}
		if($int) $base58_string = self::$alphabet{intval($int)} . $base58_string;
		return $base58_string;
	}
	
	public static function decode($base58) {
		$int_val = 0;
		for($i=strlen($base58)-1,$j=1,$base=strlen(self::$alphabet);$i>=0;$i--,$j*=$base) {
			$int_val += $j * strpos(self::$alphabet, $base58{$i});
		}
		return $int_val;
	}
}
?>

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