PHP将文件视为十六进制?

时间:2011-08-19 23:37:13

标签: 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);

   } 

} 

2 个答案:

答案 0 :(得分:3)

我不明白你的班级是如何运作的,但要转换为十六进制你可以使用

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

并将hexdump转换回源:

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

答案 1 :(得分:1)

我没有看到使用此脚本的多个文件的问题,但是当您不关闭文件时它可能会成为一个问题。最好是在函数结束/返回之前关闭文件。

相关问题