【问题标题】:Encoding/decoding string in hexadecimal and back以十六进制编码/解码字符串并返回
【发布时间】:2012-11-12 13:42:06
【问题描述】:

给定一个可能包含任何字符(包括一个unicode字符)的字符串,我怎样才能将这个字符串转换成十六进制表示,然后从十六进制中取反得到这个字符串?

【问题讨论】:

  • 您应该选择一个接受的答案。发帖人因此获得了声誉。

标签: php string unicode hex


【解决方案1】:

使用pack()unpack()

function hex2str( $hex ) {
  return pack('H*', $hex);
}

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

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

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

会产生

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

【讨论】:

  • 这太棒了,为什么 unpack() 有效,而 dechex() 无效?而且,unpack 不仅仅适用于二进制字符串?
  • 这会触发一个通知:PHP Notice: Only variables should be passed by reference
【解决方案2】:

使用这样的函数:

<?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/en/function.bin2hex.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 2020-11-11
    • 2013-01-03
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多