读取文件的二进制code ...在PHP [英] reading binary code of a file...in PHP

查看:183
本文介绍了读取文件的二进制code ...在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取二进制code(获得1和0)的文件。

How can I read the binary code(to get the 1s and 0s) of a file.

$filename = "something.mp3";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);

我试过,但它显示了一些奇怪的字符...我presume这是格式化的二进制...?我希望得到的1和0,而不是....

I tried this but it shows some strange characters... i presume that this is the formated binary...? I was hoping to get the 1's and 0's instead....

另外,我不是找只.mp3文件它可以是任何东西.e.g:.TXT,.DOC,.MP4,.PHP
为.jpg,.png等...

also i am not looking only .mp3 files it could be anything .e.g: .txt , .doc , .mp4, .php .jpg,.png etc....

感谢

推荐答案

文件存储在确实二进制形式在计算机上,但1和0一起存储在8(称为字节)组。现在,通过因为事实上一个ASCII字符psented传统上,每个字节可以被重新$ P $有可重新在一个字节psented $ P $ 256个可能值 - 这恰好与不同的ASCII的总数相一致可用字符(这不是一个巧合,但实际上是由设计)。

Files are stored on the computer in binary form indeed, but the 1s and 0s are stored together in groups of 8 (called bytes). Now, traditionally, each byte may be represented by an ASCII character because of the fact that there are 256 possible values that can be represented in a byte - which happens to coincide with the total number of different ASCII characters available (this was not a coincidence but actually by design).

话虽这么说,你做了什么从 FREAD 函数后面是你应该得到什么:即文件的内容。

That being said, what you are getting back from the fread function is what you're supposed to get: i.e. the contents of the file.

如果你想的看到 1秒的0 的你将需要打印的接收到它的基地2 重新presentation。你可以做到这一点使用功能,如 base_convert 或通过编写自己的。

If you want to see the 1s an 0s you will need to print each byte that your receive into it's base 2 representation. You can achieve that using a function such as base_convert or by writing your own.

$filename = "something.mp3";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, $fsize);
fclose($handle);

// iterate through each byte in the contents
for($i = 0; $i < $fsize; $i++)
{ 
   // get the current ASCII character representation of the current byte
   $asciiCharacter = $contents[$i];
   // get the base 10 value of the current characer
   $base10value = ord($asciiCharacter);
   // now convert that byte from base 10 to base 2 (i.e 01001010...)
   $base2representation = base_convert($base10value, 10, 2);
   // print the 0s and 1s
   echo($base2representation);
}

注意

如果你有1和0(字符的基础上再2 presentation)的字符串可以将其转换回字符,像这样:

If you have a string of 1s and 0s (the base 2 representation of a character) you can convert it back to the character like so:

$base2string = '01011010';
$base10value = base_convert($base2string, 2, 10);  // => 132
$ASCIICharacter = chr($base10value);               // => 'Z'
echo($ASCIICharacter);                             // will print Z

这篇关于读取文件的二进制code ...在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆