php 字符串、文件转化成二进制流文件
2011-07-27 23:34
281 查看
$file1 = 'F:/46.gif';
$file2 = 'F:/test.txt';
$file3 = 'F:/47.gif';
$size = filesize($file1);
echo '文件大小为:'.$size;
echo "/n<br>转化为二进制 ...";
$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;
}
$file2 = 'F:/test.txt';
$file3 = 'F:/47.gif';
$size = filesize($file1);
echo '文件大小为:'.$size;
echo "/n<br>转化为二进制 ...";
$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;
}
相关文章推荐
- 基于php常用函数总结(数组,字符串,时间,文件操作)
- Java中文件的读写及流向字符串的转化
- php读取二进制流(C语言结构体struct数据文件)的深入解析
- PHP实现文件缓存转化内存缓存
- php与ajax交互中文乱码(字符串转化)
- PHP接收二进制流并生成文件
- php中字符串转化数组,键值均为字符串指定
- java读取文件以字节流的形式读取 然后转化为字节流数组,最后经过SHA1加密生成返回16进制字符串存入数据库
- php将从数据库查询到的数据转化为json格式,并写入json文件中
- php接收二进制流(图片)生成图片文件文件
- PHP接收二进制流并生成文件
- PHP读取文件,从N行开始读取M行的代码,并以字符串类型返回
- php xml字符串转化为 array数组的代码
- PHP 时间与字符串的相互转化
- springbatch 读取csv文件时 文件中有字符串需要转换为Date类型的字段报错字符串不能转化为Date类型的解决方法
- Android 照片文件转化为而二进制流
- PHP接收二进制流并生成文件
- 基于php常用函数总结(数组,字符串,时间,文件操作)
- 把数组转化成一个xml字符串--php