Reading binary code of a file ... in PHP

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

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

I tried this, but it shows some strange characters ... I suppose it is a formatted binary? I was hoping to get 1 and 0 instead.

Also, I am not looking only for .mp3 files, it can be anything .eg: .txt , .doc , .mp4 , .php , .jpg , .png , etc.

+4
source share
3 answers

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

As the saying goes, what you get from the fread function is what you should get: that is, the contents of the file.

If you want to see 1s an 0s , you will need to print each byte to get base 2 in it. You can achieve this with a function like 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 (ie 01001010...) $base2representation = base_convert($base10value, 10, 2); // print the 0s and 1s echo($base2representation); } 

Note

If you have a string of 1s and 0s (a basic representation of 2 characters), you can convert it back to a character as follows:

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

Here you go, 1s and 0s:

  $ filename = "something.mp3";
 $ handle = fopen ($ filename, "rb");
 $ contents = fread ($ handle, filesize ($ filename));
 for ($ i = 0; $ i <strlen ($ contents); $ i ++) {
     $ binary = sprintf ("% 08d", base_convert (ord ($ contents [$ i]), 10, 2));
     echo $ binary.  "";
 }
 fclose ($ handle);
+5
source

Why not use the PHP decbin function?

 for($i = 0; $i < $fsize; $i++){ $base10value = ord($contents[$i]); echo decbin($base10value); } 
+1
source

Source: https://habr.com/ru/post/1300302/


All Articles