php怎样将二进制流存到文件中

来源:互联网 发布:淘宝闲置物品怎么买 编辑:程序博客网 时间:2024/06/06 03:08
$str = 0x8000;
  
echo $str2 base_convert($str, 16, 2);
echo '';
echo base_convert($str2, 2, 16);
[code]
  
字符串 文件等 可以考虑用 pack 和 unpack 转化成二进制
  
[code=PHP]
$file1 'F:/46.gif';           //随便拷一个图片作为测试用
$file2 'F:/test.txt';         //生成的二进制流保存在这个文件里
$file3 'F:/47.gif';           //由二进制流还原成的文件
  
$size filesize($file1);
  
echo '文件大小为:'.$size;
echo "\n转化为二进制 ...";
  
$content file_get_contents($file1);
$content = bstr2bin($content);
  
  
$fp fopen($file2'w');
fwrite($fp$content);
fclose($fp);
  
$size2 filesize($file2);
  
echo '转化成二进制后文件大小为:'.$size2;
  
$content = bin2bstr($content);
  
$fp fopen($file3'w');
fwrite($fp$content);
fclose($fp);
  
  
function bin2bstr($input)
// Convert a binary expression (e.g., "100111") into a binary-string
{
  if (!is_string($input)) return null; // Sanity check
  
  // Pack into a string
  $input str_split($input, 4);
  $str '';
  foreach ($input as $v)
  {
      $str .= base_convert($v, 2, 16);
  }
    
  $str =  pack('H*'$str);
    
  return $str;
}
  
function bstr2bin($input)
// Binary representation of a binary-string
{
  if (!is_string($input)) return null; // Sanity check
  
  // Unpack as a hexadecimal string
  $value = unpack('H*'$input);
    
  // Output binary representation
  $value str_split($value[1], 1);
  $bin '';
  foreach ($value as $v)
  {
      $b str_pad(base_convert($v, 16, 2), 4, '0', STR_PAD_LEFT);
        
      $bin .= $b;
  }
    
  return $bin;
}
0 0