整形轉化成 2二進位制 可以用 base_convert:
$str = 0x8000;
echo $str2 = base_convert($str, 16, 2);
echo "<br>";
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<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");
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
// 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;
整形轉化成 2二進位制 可以用 base_convert:
$str = 0x8000;
echo $str2 = base_convert($str, 16, 2);
echo "<br>";
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<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;
}