Never been to DZone Snippets before?

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

base58 conversion (See related posts)

Super quick note, hopefully sufficient info.

The format for the short photo URLs is

flic.kr/p/{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: http://www.flickr.com/groups/api/discuss/72157616713786392/



    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;
    }

Comments on this post

stvkoch posts on Aug 17, 2010 at 13:25
funciona assim tambem para 36 bits!
base_convert( $num, 10, 36)

You need to create an account or log in to post comments to this site.


Click here to browse all 7718 code snippets

Related Posts