Skip to content

Instantly share code, notes, and snippets.

@srigi
Created June 29, 2017 11:50
Show Gist options
  • Save srigi/3384539a494d0c4a3b18988dcf835e1d to your computer and use it in GitHub Desktop.
Save srigi/3384539a494d0c4a3b18988dcf835e1d to your computer and use it in GitHub Desktop.
UUID (hex) to base62 and vice-versa
<?php
class Base62
{
const BASE_OCT = 8;
const BASE_DEC = 10;
const BASE_HEX = 16;
const BASE_62 = 62;
const POOL = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
/**
* @param int $num
* @param int $inputBase
* @param int $outputBase
* @return string
*/
public static function convert($num, $inputBase = self::BASE_DEC, $outputBase = self::BASE_62)
{
if (!extension_loaded('gmp')) {
throw new LogicException('Please enable GMP extension to use base62 conversion');
}
if ($inputBase === 16) {
$num = preg_replace('/[^0-9A-Fa-f]/i', '', $num); // remove any non-hex characters
}
$gmpNum = gmp_init($num, $inputBase);
$gmpBase = gmp_init($outputBase, 10);
list($quotient, $remainder) = gmp_div_qr($gmpNum, $gmpBase);
$out = self::POOL[gmp_intval($remainder)];
while (gmp_intval($quotient)) {
list($quotient, $remainder) = gmp_div_qr($quotient, $gmpBase);
$out = self::POOL[gmp_intval($remainder)] . $out;
}
return $out;
}
}
<?php
require_once __DIR__ . '/Base62.php';
?>
<style>
body { margin:1rem auto; max-width:36rem; }
p { text-align:center; }
pre { white-space:pre-wrap; word-wrap:break-word; }
td { border:1px solid lightgray; min-width:10rem; padding:0.25rem 1rem; }
</style>
<pre>
<table>
<tr><th><h2>dec</h2> </th><th>hex</th> <th>base62</th></tr>
<?php $decNums = [
'000',
'001',
'002',
'003',
'010',
'015',
'016',
'017',
'061',
'062',
'063',
'064',
] ?>
<?php foreach ($decNums as $num) { ?>
<tr>
<td><?= $num ?></td>
<td><?= Base62::convert($num, Base62::BASE_DEC, Base62::BASE_HEX) ?></td>
<td><?= Base62::convert($num) ?></td>
</tr>
<?php } ?>
</table>
<table>
<tr><th><h2>hex</h2></th> <th>dec</th> <th>base62</th></tr>
<?php $hexNums = [
'000',
'001',
'002',
'003',
'00a',
'00f',
'010',
'011',
'03d',
'03e',
'03f',
'040',
'ab1ba25a-3956',
'4d1b-858b',
'adcdd132e691',
] ?>
<?php foreach ($hexNums as $num) { ?>
<tr>
<td><?= $num ?></td>
<td><?= Base62::convert($num, Base62::BASE_HEX, Base62::BASE_DEC) ?></td>
<td><?= Base62::convert($num, Base62::BASE_HEX) ?></td>
</tr>
<?php } ?>
</table>
<table>
<tr><th><h2>base62</h2></th> <th>dec</th> <th>hex</th></tr>
<?php $base62Nums = [
'0',
'1',
'2',
'3',
'A',
'F',
'G',
'H',
'z',
'10',
'11',
'12',
'rQDxyr5S',
'1PY1H9',
'sGPeBjO5',
] ?>
<?php foreach ($base62Nums as $num) { ?>
<tr>
<td><?= $num ?></td>
<td><?= Base62::convert($num, Base62::BASE_62, Base62::BASE_DEC) ?></td>
<td><?= Base62::convert($num, Base62::BASE_62, Base62::BASE_HEX) ?></td>
</tr>
<?php } ?>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment