Base62 encode/decode with AS3 and PHP

When passing numeric values to an application using a URL, sometimes one wants to keep them short and have them alphanumeric rather than numeric. Base64 contains a couple of characters that are not URL friendly, and if you remove them you are left with Base62.

I needed classes to handle that in both AS3 and PHP with static access, and based on this snippet I came up with the following:

PHP:

<?php

class Base62

{

public static $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

public static $base = 62;

public static function encode($val)

{

// can't handle numbers larger than 2^31-1 = 2147483647

$str = '';

do {

$i = $val % self::$base;

$str = self::$chars[$i] . $str;

$val = ($val - $i) / self::$base;

} while($val > 0);

return $str;

}

public static function decode($str)

{

$len = strlen($str);

$val = 0;

$arr = array_flip(str_split(self::$chars));

for ($i = 0; $i < $len; ++$i)

{

$val += $arr[$str[$i]] * pow(self::$base, $len-$i-1);

}

return $val;

}

}

?>

AS3:

package com.blixtsystems.utils

{

/**

* Encode/Decode Base62

* @author leo@blixtsystems.com

*/

public class Base62

{

public static var chars:String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

public static var base:int = 62;

public function Base62()

{

}

public static function encode(val:Number):String

{

var str:String = '';

var i:int;

while(val > 0)

{

i = val % base;

str = chars.substr(i,1) + str;

val = (val - i) / base;

}

return str;

}

public static function decode(str:String):Number

{

var len:int = str.length;

var val:int = 0;

for (var i:int = 0; i < len; ++i)

{

val += chars.indexOf(str.substr(i,1)) * Math.pow(base, len-i-1);

}

return val;

}

}

}

Share/Bookmark