php 将十六进制转换为 ascii 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7488538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:46:51  来源:igfitidea点击:

Convert hex to ascii characters

phpencodingdecoding

提问by Dziamid

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?

是否可以用0-9a-zA-Z字符序列表示一个十六进制字符序列(0-9A-F),所以结果序列更小,可以解码?

For example:

例如:

$hex = '5d41402abc4b2a76b9719d911017c592';
echo $string = encode($hex); // someASCIIletters123
echo decode(string) == $hex; //true

采纳答案by Jon

You can trivially adapt the solution I presented hereusing the function base_convert_arbitrary.

您可以使用函数轻松调整我在此处介绍的解决方案base_convert_arbitrary

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

编辑:我没有仔细阅读:) Base 16 到 base 62 仍然非常可行,如上所述。

See it in action.

看到它在行动

回答by Andrew

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)

(来自http://www.linux-support.com/cms/php-convert-hex-strings-to-ascii-strings/)(像这个 javascript 工具一样工作:http: //www.dolcevie.com/js/转换器.html)

回答by Marc B

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.

回答by Jon Skeet

Well, something similar, yes... parse the hex characters as a binary value, then convert to base64. That uses a littlebit 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_encodeto perform the encoding if so.

嗯,类似的东西,是的...将十六进制字符解析为二进制值,然后转换为 base64。这比 0-9 az AZ使用的多一点,但只使用了几个字符。除了那 62 个字符之外,您还可以使用其他三个字符吗?base64_encode如果是这样,您可以使用来执行编码。

(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.)

(您可以改为转换为 base32,但这不会那么紧凑。转换为不是 2 的幂的基数也是可行的,但不太吸引人。)

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 packto do the original parsing...

如果您的输入序列有奇数个字符,您还需要某种方式来表示最后的半字节。在调用pack进行原始解析之前,您可能需要考虑一下...