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

后端 未结 8 684
自闭症患者
自闭症患者 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: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;
    }
    

提交回复
热议问题