在PHP中将HEX转换为ANSI

时间:2015-11-14 17:17:26

标签: php hex ansi

我正在编写一种十六进制查看器,用户输入可执行文件,页面返回十六进制转储和ANSI旁边的表示。 (实际上我不知道为什么使用ANSI,但我正在使用的十六进制编辑器使用此返回结果)

这样的事情:

enter image description here

但是我的代码返回了这个:

enter image description here

我不知道我做错了什么,我尝试了另外的代码,它返回了所有的字符,但我需要让一些字节返回一个点“。”,正如你在打印中看到的那样。

这是我的代码:

 <?php

function hex2str($hex) {
    $str = '';
    for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
    return $str;
} // i found this function on internet to convert HEX to String

$nome = "apateDNS.exe";//the name of the file
$arquivo = fopen($nome, "r");
$read = fread($arquivo,filesize($nome));
$hex = bin2hex($read);// return the hex of the binary
$hehe = chunk_split(strtoupper($hex), 2, " ");// split the hex each 2 bytes
$haha = str_split($hehe, 48); //split the hex each 48 characters (32 bytes + 16 blank spaces)
foreach($haha as $linha => $i){
    echo "0000000".dechex($linha*16);
    echo " ".$i." ".hex2str($i)."<br>";
}
?>

已解决:我忘记删除功能中的空格...

$hex = str_replace(" ", "", $hex);

1 个答案:

答案 0 :(得分:1)

function hex2str($hex) {
    $str = '';
    for($i=0;$i<strlen($hex);$i+=2) {
        $decValue = hexdec(substr($hex,$i,2));
        if($decValue < 32) {
            $str .= '.';
        } else {
            $str .= chr($decValue);
        }
    }
        return $str;
}

要生成所有十六进制代码及其翻译的表格,请使用以下代码:

for($x = 0; $x < 16; $x++) {
    $bin = $txt = array();
    for($y = 0; $y < 16; $y++) {        
        $num = dechex($x * 16 + $y);
        if(strlen($num) == 1) $num = '0' . $num;
        $bin[] = $num;
        $txt[] = hex2str($num);

    }
    echo (implode(' ',$bin) . '     ' . implode(' ',$txt)) . '<br/>';
}