Skip to content

Instantly share code, notes, and snippets.

@dalabarge
Created June 20, 2019 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalabarge/1a63a20af8b0c3db586924cc1ef20ffb to your computer and use it in GitHub Desktop.
Save dalabarge/1a63a20af8b0c3db586924cc1ef20ffb to your computer and use it in GitHub Desktop.
A UUID to short ID (SID) convertor based on CRC64 to Base36
<?php
/**
* @return array
*/
function crc64Table()
{
$crc64tab = [];
// ECMA polynomial
$poly64rev = (0xC96C5795 << 32) | 0xD7870F42;
// ISO polynomial
// $poly64rev = (0xD8 << 56);
for ($i = 0; $i < 256; $i++)
{
for ($part = $i, $bit = 0; $bit < 8; $bit++) {
if ($part & 1) {
$part = (($part >> 1) & ~(0x8 << 60)) ^ $poly64rev;
} else {
$part = ($part >> 1) & ~(0x8 << 60);
}
}
$crc64tab[$i] = $part;
}
return $crc64tab;
}
/**
* @param string $string
* @param string $format
* @return mixed
*
* Formats:
* crc64('php'); // afe4e823e7cef190
* crc64('php', '0x%x'); // 0xafe4e823e7cef190
* crc64('php', '0x%X'); // 0xAFE4E823E7CEF190
* crc64('php', '%d'); // -5772233581471534704 signed int
* crc64('php', '%u'); // 12674510492238016912 unsigned int
*/
function crc64($string, $format = '%x')
{
static $crc64tab;
if ($crc64tab === null) {
$crc64tab = crc64Table();
}
$crc = 0;
for ($i = 0; $i < strlen($string); $i++) {
$crc = $crc64tab[($crc ^ ord($string[$i])) & 0xff] ^ (($crc >> 8) & ~(0xff << 56));
}
return sprintf($format, $crc);
}
include 'vendor/autoload.php';
$uuid = strtoupper(str_replace('-', '', \Ramsey\Uuid\Uuid::uuid4()->toString()));
var_dump($uuid);
$crc = crc64($uuid, '%X');
var_dump($crc);
$hex = substr($crc, 0, 5);
$sid = strtoupper(base_convert($hex, 16, 36));
var_dump($sid);
@dalabarge
Copy link
Author

$ php sid.php
string(32) "9176A6A0D5354A5BB06AE33F59BAAB89"
string(16) "B80294D0AA1A89B6"
string(4) "G5K9"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment