Converting a Number Base 10 to Base 62 (A-Za-Z0-9)

converting a number base 10 to base 62 (a-zA-Z0-9)

OLD: A quick and dirty solution can be to use a function like this:

function toChars($number) {
$res = base_convert($number, 10,26);
$res = strtr($res,'0123456789','qrstuvxwyz');
return $res;
}

The base convert translate your number to a base where the digits are 0-9a-p
then you get rid of the remaining digits with a quick char substitution.

As you may observe, the function is easily reversible.

function toNum($number) {
$res = strtr($number,'qrstuvxwyz','0123456789');
$res = base_convert($number, 26,10);
return $res;
}

By the way, what would you use this function for?


Edit:

Based on the question change and on the @jnpcl answer, here is a set of functions that performs the base conversion without using pow and log (they take half the time to complete the tests).

The functions work for integer values only.

function toBase($num, $b=62) {
$base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$r = $num % $b ;
$res = $base[$r];
$q = floor($num/$b);
while ($q) {
$r = $q % $b;
$q =floor($q/$b);
$res = $base[$r].$res;
}
return $res;
}

function to10( $num, $b=62) {
$base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$limit = strlen($num);
$res=strpos($base,$num[0]);
for($i=1;$i<$limit;$i++) {
$res = $b * $res + strpos($base,$num[$i]);
}
return $res;
}

The test:

for ($i = 0; $i<1000000; $i++) {
$x = toBase($i);
$y = to10($x);
if ($i-$y)
echo "\n$i -> $x -> $y";
}

Convert MD5 to base62 for URL

I'm going to suggest a different thing here.. Since you are only interested in using a decimal chunk of the md5 hash why don't you use any other short numeric hash like CRC32 or Adler? Here is an example:

$hash = sprintf('%u', crc32('your string here'));

This will produce a 8 digit hash of your string.

EDIT: I think I misunderstood you, here are some functions that provide conversions to and from bases up to 62.

EDIT (Again): To work with arbitrary length numbers you must use either the bc_math or the GMP extension, here is a function that uses the bc_math extension and can also convert from base 2 up to base 62. You should use it like this:

echo bc_base_convert(md5('your url here'), 16, 62); // public base 62 hash

and the inverse:

echo bc_base_convert('base 62 encoded value here', 62, 16); // private md5 hash

Hope it helps. =)

Map unique number to a unique string of 6 characters

If you want to make A-Z a-z 0-9 to be the alphabet as you noticed you have base 62 number system. So encode the unique rowid in base 62, there is a standard algorithm to do so. If your application allows (needs) it you can add a few more printable characters like '+', '/', '!', '@'.. so you get more uniques. The ready made answer is base64 encoding, widely used.



Related Topics



Leave a reply



Submit