sourcetip

PHP는 문자열을 16진수로 변환하고 16진수를 문자열로 변환합니다.

fileupload 2023. 8. 6. 10:17
반응형

PHP는 문자열을 16진수로 변환하고 16진수를 문자열로 변환합니다.

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

제가 확인해보니 XOR을 사용하여 암호화를 할 때 이것을 알게 되었습니다.

나는 그 끈을 가지고 있습니다."this is the test"키로 XOR을 한 후, 나는 문자열로 결과를 얻습니다.↕↑↔§P↔§P ♫§T↕§↕그 후에 함수 strToHex()로 hex로 변환하려고 했는데 이것들을 받았습니다.12181d15501d15500e15541215712그리고 나서, 나는 hexToStr() 함수로 테스트를 했고, 나는.↕↑↔§P↔§P♫§T↕§q그렇다면, 이 문제를 해결하려면 어떻게 해야 할까요?이 2가지 스타일 값을 변환할 때 왜 잘못된 것입니까?

여기까지 와서 (이진) 문자열의 16진수 표현을 찾고 있는 사람들을 위한 것입니다.

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

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

문서: bin2hex, hex2bin.

Ord($char)가 16 미만인 모든 문자에 대해 길이가 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";

PHP:

16진수로 문자열:

implode(unpack("H*", $string));

16진수에서 문자열로:

pack("H*", $hex);

제가 사용하는 것은 다음과 같습니다.

function strhex($string) {
  $hexstr = unpack('H*', $string);
  return array_shift($hexstr);
}
function hexToStr($hex){
    // Remove spaces if the hex string has spaces
    $hex = str_replace(' ', '', $hex);
    return hex2bin($hex);
}
// Test it 
$hex    = "53 44 43 30 30 32 30 30 30 31 37 33";
echo hexToStr($hex); // SDC002000173

/**
 * Test Hex To string with PHP UNIT
 * @param  string $value
 * @return 
 */
public function testHexToString()
{
    $string = 'SDC002000173';
    $hex    = "53 44 43 30 30 32 30 30 30 31 37 33";
    $result = hexToStr($hex);

    $this->assertEquals($result,$string);
}

@bill-shirley를 사용하여 약간의 추가를 포함한 답변

function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}

용도:

  $str = "Go placidly amidst the noise";
  $hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
  $strstr = hex_to_str($str);// Go placidly amidst the noise

다음 코드를 사용하여 이미지를 16진수 문자열로 변환할 수 있습니다.

<?php
$image = 'sample.bmp';
$file = fopen($image, 'r') or die("Could not open $image");
while ($file && !feof($file)){
$chunk = fread($file, 1000000); # You can affect performance altering
this number. YMMV.
# This loop will be dog-slow, almost for sure...
# You could snag two or three bytes and shift/add them,
# but at 4 bytes, you violate the 7fffffff limit of dechex...
# You could maybe write a better dechex that would accept multiple bytes
# and use substr... Maybe.
for ($byte = 0; $byte < strlen($chunk); $byte++)){
echo dechex(ord($chunk[$byte]));
}
}
?>

답은 절반밖에 없지만 유니코드(utf-8) 지원이 추가되어 유용했으면 좋겠습니다.

    /**
     * hexadecimal to unicode character
     * @param  string  $hex
     * @return string
     */
    function hex2uni($hex) { 
      $dec = hexdec($hex);
        if($dec < 128) {
            return chr($dec);
        }
        if($dec < 2048) {
            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
        } else {
            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
        }
        return $utf . chr(128 + ($dec % 64));
    }

문자열로

    var_dump(hex2uni('e641'));

기준: http://www.php.net/manual/en/function.chr.php#Hcom55978

언급URL : https://stackoverflow.com/questions/14674834/php-convert-string-to-hex-and-hex-to-string

반응형