The standard string representation of GUID takes about 36 characters. Which is very nice, but also really wasteful. I am wondering, how to encode it in the shortest possible
An arbitrary GUID? The "naive" algorithm will produce optimal results. The only way to compress a GUID further is to make use of patterns in the data excluded by your "arbitrary" constraint.
I agree with the Base64 approach. It will cut back a 32-letter UUID to 22-letter Base64.
Here are simple Hex <-> Base64 converting functions for PHP:
function hex_to_base64($hex){
$return = '';
foreach(str_split($hex, 2) as $pair){
$return .= chr(hexdec($pair));
}
return preg_replace("/=+$/", "", base64_encode($return)); // remove the trailing = sign, not needed for decoding in PHP.
}
function base64_to_hex($base64) {
$return = '';
foreach (str_split(base64_decode($base64), 1) as $char) {
$return .= str_pad(dechex(ord($char)), 2, "0", STR_PAD_LEFT);
}
return $return;
}