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

Joe*_*yen 43 php string hex

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 48

对于任何带有ord($ char)<16的char,你会得到一个只有1长的HEX.你忘了添加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";
Run Code Online (Sandbox Code Playgroud)

  • 在 strToHex 函数中,作为整个 dechex() 和 substr -2 的替代方案,可以只使用: `$hex .= sprintf('%02.x', $ord);` (2认同)

Phi*_*ber 40

对于那些最终在这里并且只是寻找(二进制)字符串的十六进制表示的人.

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

hex2bin('74686174277320616c6c20796f75206e656564');
# that's all you need
Run Code Online (Sandbox Code Playgroud)


زيا*_*ياد 28

PHP:

字符串到十六进制

implode(unpack("H*", $string));
Run Code Online (Sandbox Code Playgroud)

十六进制到字符串

pack("H*", $hex);
Run Code Online (Sandbox Code Playgroud)


小智 13

这是我使用的:

function strhex($string) {
  $hexstr = unpack('H*', $string);
  return array_shift($hexstr);
}
Run Code Online (Sandbox Code Playgroud)