DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Base58 Conversion

  • submit to reddit
        Super quick note, hopefully sufficient info.

The format for the short photo URLs is{short-photo-id}

A short photo id is a base58 conversion of the photo id. Base58 is like base62 [0-9a-zA-Z] with some characters removed to make it less confusing when printed. (namely 0, O, I, and l).

So that leaves an alphabet of: 123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ

I'm including below a variation of the code we use to do base conversion. Note it doesn't use modulus because PHP's modulus operator overflows for large numbers (like photo ids)

//Original post:

    function base_encode($num, $alphabet) {
    $base_count = strlen($alphabet);
    $encoded = '';
    while ($num >= $base_count) {
    $div = $num/$base_count;
    $mod = ($num-($base_count*intval($div)));
    $encoded = $alphabet[$mod] . $encoded;
    $num = intval($div);

    if ($num) $encoded = $alphabet[$num] . $encoded;

    return $encoded;

    function base_decode($num, $alphabet) {
    $decoded = 0;
    $multi = 1;
    while (strlen($num) > 0) {
    $digit = $num[strlen($num)-1];
    $decoded += $multi * strpos($alphabet, $digit);
    $multi = $multi * strlen($alphabet);
    $num = substr($num, 0, -1);

    return $decoded;


Snippets Manager replied on Mon, 2006/06/19 - 11:07am

funciona assim tambem para 36 bits! base_convert( $num, 10, 36)