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);
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.
Also I am not looking only .mp3 files it could be anything .e.g: .txt , .doc , .mp4, .php, .jpg, .png etc….
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).
That being said, what you are getting back from the
freadfunction is what you’re supposed to get: i.e. the contents of the file.If you want to see the
1s an 0syou 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.NOTE
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: