且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-21 17:47:29

对于任何带ord的字符($ char)< 16你得到一个只有1长的HEX。

 <?php 
function strToHex($ string){
$ hex =''; ($ i = 0; $ i< strlen($ string); $ i ++){
$ ord = ord($ string [$ i]);

$ hexCode = dechex($ ord);
$ hex。= substr('0'。$ hexCode,-2);
}
return strToUpper($ hex);
}
函数hexToStr($ hex){
$ string ='';
for $($ i = 0; $ i $ string。= chr(hexdec($ hex [$ i]。$ hex [$ I + 1]));
}
return $ string;
}


//测试
header('Content-Type:text / plain');
函数测试($ expected,$ actual,$ success){
if($ expected!== $ actual){
echoExpected:'$ expected'\\\
;
echoActual:'$ actual'\\\
;
回声\\\
;
$ success = false;
}
返回$ 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↕§↕')),$成功);

echo $ success? 成功:\失败;


I got the problem when convert between this 2 type in PHP. This is the code I searched in google

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;
}

I check it and found out this when I use XOR to encrypt.

I have the string "this is the test", after XOR with a key, I have the result in string ↕↑↔§P↔§P ♫§T↕§↕. After that, I tried to convert it to hex by function strToHex() and I got these 12181d15501d15500e15541215712. Then, I tested with the function hexToStr() and I have ↕↑↔§P↔§P♫§T↕§q. So, what should I do to solve this problem? Why does it wrong when I convert this 2 style value?

For any char with ord($char) < 16 you get a HEX back which is only 1 long. You forgot to add 0 padding.

This should solve it:

<?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";