PHP 将字符串转换为十六进制,将十六进制转换为字符串

2022-08-30 09:13:31

在PHP中转换这2种类型时,我遇到了问题。这是我在谷歌中搜索的代码

function strToHex($string){
    $hex='';
    for ($i=0; $i < strlen($string); $i++){
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}


function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

我检查了它,当我使用XOR加密时发现了这一点。

我有字符串,在带有键的XOR之后,我有字符串中的结果。之后,我试图通过函数strToHex()将其转换为十六进制,我得到了这些。然后,我用函数hexToStr()进行了测试,我有.那么,我该怎么做才能解决这个问题呢?为什么当我转换这个2样式值时它是错误的?"this is the test"↕↑↔§P↔§P ♫§T↕§↕12181d15501d15500e15541215712↕↑↔§P↔§P♫§T↕§q


答案 1

对于最终来到这里并且只是寻找(二进制)字符串的十六进制表示形式的人。

bin2hex("that's all you need");
# 74686174277320616c6c20796f75206e656564

hex2bin('74686174277320616c6c20796f75206e656564');
# that's all you need

Doc: bin2hexhex2bin.


答案 2

对于任何具有ord($char)<16的字符,您都会得到一个只有1长的十六进制。您忘记添加 0 填充。

这应该可以解决它:

<?php
function strToHex($string){
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}
function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}


// Tests
header('Content-Type: text/plain');
function test($expected, $actual, $success) {
    if($expected !== $actual) {
        echo "Expected: '$expected'\n";
        echo "Actual:   '$actual'\n";
        echo "\n";
        $success = false;
    }
    return $success;
}

$success = true;
$success = test('00', strToHex(hexToStr('00')), $success);
$success = test('FF', strToHex(hexToStr('FF')), $success);
$success = test('000102FF', strToHex(hexToStr('000102FF')), $success);
$success = test('↕↑↔§P↔§P ♫§T↕§↕', hexToStr(strToHex('↕↑↔§P↔§P ♫§T↕§↕')), $success);

echo $success ? "Success" : "\nFailed";

推荐