2011-08-19 142 views
0

我期待已久的一種方式來查看文件用十六進制前一段時間,發現:PHP查看文件爲十六進制?

class Hex 
{ 

    var $file; 
    var $hex; 

    function __construct($file) 
    { 
     $this->file = $file; 
    } 


    function gethex() 
    { 
     $handle = fopen($this->file, 'r') or die('Permission?'); 

     while(!feof($handle)) 
     { 
      foreach(unpack('C*',fgets($handle)) as $dec) 
      { 
       $tmp = dechex($dec); 
       $this->hex[] .= strtoupper(str_repeat('0',2-strlen($tmp)).$tmp);  
      } 
     } 

     return join($this->hex); 
    } 

    function writehex($hexcode) 
    { 

     foreach(str_split($hexcode,2) as $hex) 
     { 
     $tmp .= pack('C*', hexdec($hex)); 
     } 

     $handle = fopen($this->file, 'w+') or die('Permission?'); 
     fwrite($handle, $tmp); 

    } 

} 

它爲一個文件偉大的工作,但我覺得我遇到了問題,試圖多辦呢文件。腳本有什麼問題嗎?它應該關閉文件的某個地方嗎?我應該在使用它們之後刪除它的實例嗎?

這會是更好的?:

class Hex 
{ 

    var $file; 
    var $hex; 

    function __construct($file) 
    { 
     $this->file = $file; 
    } 


    function gethex() 
    { 
     $handle = fopen($this->file, 'r') or die('Permission?'); 

     while(!feof($handle)) 
     { 
      foreach(unpack('C*',fgets($handle)) as $dec) 
      { 
       $tmp = dechex($dec); 
       $this->hex[] .= strtoupper(str_repeat('0',2-strlen($tmp)).$tmp);  
      } 
     } 
     fclose($handle); 
     return join($this->hex); 
    } 

    function writehex($hexcode) 
    { 

     foreach(str_split($hexcode,2) as $hex) 
     { 
     $tmp .= pack('C*', hexdec($hex)); 
     } 

     $handle = fopen($this->file, 'w+') or die('Permission?'); 
     fwrite($handle, $tmp); 
     fclose($handle); 

    } 

} 
+1

爲什麼不乾脆使用二進制模式? – Pwnna

+1

http://php.net/manual/en/function.bin2hex.php –

+0

對於這一切,我還是一個小菜鳥,我習慣在HxD中離線編輯文件。稍後我可能會嘗試更改它 – mowwwalker

回答

1

我沒有看到與此腳本多個文件的問題,但是當你不關閉文件,它可能成爲一個問題。最好的辦法是在函數結束之前關閉文件。

+0

像第二個代碼? – mowwwalker

3

我不明白你的類是如何工作的,但要轉換爲十六進制,你可以使用

$hex = unpack("H*", file_get_contents($filename)); 
$hex = current($hex); 

和一個hexdump都可以轉換回源:

$chars = pack("H*", $hex);