将字符串进行十六进制编码/解码并还原为字符串

6

如何将包含任何字符(包括Unicode字符)的字符串转换为十六进制表示形式,然后反转并从十六进制中获取该字符串?


2
你应该选择一个已被接受的答案。发布者会因此获得声望积分。 - fool4jesus
2个回答

18
使用pack()unpack()函数:
function hex2str($hex) {
  return pack('H*', $hex);
}

function str2hex($str) {
  $unpacked = unpack('H*', $str);
  return array_shift($unpacked);
}

$txt = 'This is test';
$hex = str2hex($txt);
$str = hex2str($hex);

echo "{$txt} => {$hex} => {$str}\n";

会产生

这是测试 => 546869732069732074657374 => 这是测试


这太棒了,为什么unpack()能工作,而dechex()不能?而且,unpack不仅适用于二进制字符串? - bluantinoo
1
这将触发一个通知:PHP注意:只有变量应该通过引用传递 - Potherca
啊,是关于直接将unpack()的结果传递给array_shift()的问题。已修复,谢谢。 - undefined

1

使用类似这样的函数:

<?php
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= dechex(ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// Look what happens when ord($str{$i}) is 0...15
// you get a single digit hexadecimal value 0...F

// bin2hex($str) could return something like 4a3,
// decimals(74, 3), whatever the binary value is of those.

function hex2bin($str) {
    $bin = "";
    $i = 0;
    do {
        $bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
        $i += 2;
    } while ($i < strlen($str));
    return $bin;
}

// hex2bin("4a3") just broke. Now what?

// Using sprintf() to get it right.
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= sprintf("%02x", ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// now using whatever the binary value of decimals(74, 3)
// and this bin2hex() you get a hexadecimal value you can
// then run the hex2bin function on. 4a03 instead of 4a3.
?>

来源:http://php.net/manual/zh/function.bin2hex.php


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接