What is the most efficient way to encode an arbitrary GUID into readable ASCII (33-127)?

后端 未结 8 644
自闭症患者
自闭症患者 2020-11-30 22:08

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

相关标签:
8条回答
  • 2020-11-30 22:35

    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.

    0 讨论(0)
  • 2020-11-30 22:38

    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;
    }
    
    0 讨论(0)
提交回复
热议问题