您的位置:首页 > 编程语言 > PHP开发

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: