php的字符串转2进制函数

时间:2024-09-27 22:35:56
<?php

$file1 = '16.jpg';
$file2 = 'test.txt';
$file3 = '47.jpg';
$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_r(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;
} ?>