Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Convert a big binary file to a readable file

I am having problems with this simple script...

<?php
$file = "C:\\Users\\Alejandro\\Desktop\\integers\\integers";

$file = file_get_contents($file, NULL, NULL, 0, 34359738352);

echo $file;
?>

It gives me always this error:

file_get_contents(): length must be greater than or equal to zero

I am really tired, can someone help me?

EDIT: After dividing the file in 32 parts...

The error is

PHP Fatal error:  Allowed memory size of 1585446912 bytes exhausted (tried to al
locate 2147483648 bytes)

Fatal error: Allowed memory size of 1585446912 bytes exhausted (tried to allocat
e 2147483648 bytes)

EDIT (2):

Now the deal is to convert this binary file into a list of numbers from 0 to (2^31)-1 That is why I need to read the file, so I can convert the binary digits to decimal numbers.

like image 960
Alex Avatar asked Dec 06 '25 14:12

Alex


1 Answers

Looks like your file path is missing a backslash, which could be causing file_load_contents() to fail loading the file.

Try this instead:

$file = "C:\\\\Users\\Alejandro\\Desktop\\integers\\integers";

EDIT: Now that you can read your file, we're finding that because your file is so large, it's exceeding your memory limit and causing your script to crash.

Try buffering one piece at a time instead, so as not to exceed memory limits. Here's a script that will read binary data, one 4-byte number at a time, which you can then process to suit your needs.

By buffering only one piece at a time, you allow PHP to use only 4 bytes at a time to store the file's contents (while it processes each piece), instead of storing the entire contents in a huge buffer and causing an overflow error.

Here you go:

$file = "C:\\\\Users\\Alejandro\\Desktop\\integers\\integers";

// Open the file to read binary data
$handle = @fopen($file, "rb"); 
if ($handle) { 
   while (!feof($handle)) { 
       // Read a 4-byte number
       $bin = fgets($handle, 4);
       // Process it
       processNumber($bin); 
   } 
   fclose($handle); 
}

function processNumber($bin) {
    // Print the decimal equivalent of the number
    print(bindec($bin)); 
}
like image 134
Steven Moseley Avatar answered Dec 11 '25 19:12

Steven Moseley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!