Convert hex to ascii characters

前端 未结 5 1049
攒了一身酷
攒了一身酷 2020-12-03 15:12

Is it possible to represent a sequence of hex characters (0-9A-F) with a sequence of 0-9a-zA-Z characters, so the the result sequence is smaller and can be decoded?

相关标签:
5条回答
  • 2020-12-03 15:18

    You can trivially adapt the solution I presented here using the function base_convert_arbitrary.

    Edit: I had not read carefully enough :) Base 16 to base 62 is still very doable, as above.

    See it in action.

    0 讨论(0)
  • 2020-12-03 15:24

    I think you're looking for this:

    function hex2str($hex) {
        $str = '';
        for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
        return $str;
    }
    

    (From http://www.linux-support.com/cms/php-convert-hex-strings-to-ascii-strings/) (Works like this javascript tool: http://www.dolcevie.com/js/converter.html)

    0 讨论(0)
  • 2020-12-03 15:28

    You mean want to convert a string of hex digits into actual hex values?

    $hex_string = "A1B2C3D4F5"; // 10 chars/bytes
    $packed_string = pack('H*', $hex_string); // 0xA1B2C3D4F5 // 5 chars/bytes.
    
    0 讨论(0)
  • 2020-12-03 15:35

    The built-in php functions may help some landing here on a search:

    // https://www.php.net/manual/en/function.hex2bin
    $hex = '6578616d706c65206865782064617461';
    echo hex2bin($hex); // example hex data
    
    0 讨论(0)
  • 2020-12-03 15:38

    Well, something similar, yes... parse the hex characters as a binary value, then convert to base64. That uses a little bit more than 0-9 a-z A-Z, but only a few more characters. Are you okay to use three other characters in addition to those 62? You can use base64_encode to perform the encoding if so.

    (You could convert to base32 instead, but that wouldn't be as compact. Converting to bases which aren't powers of 2 is also feasible, but less appealing.)

    You'd also need some way of representing a final half-byte if your input sequence had an odd number of characters. You'll probably want to think about that before calling pack to do the original parsing...

    0 讨论(0)
提交回复
热议问题