here is the skinny (scroll down to see the problem): I am doing Huffman Encoding to compress a file using PHP (for a project). I have made the map, and made everything into a string like so:
00101010001100001110011101001101111011111011
Now, I need to convert that into an actual binary string, in its current state, it is only a string of 1s and 0s.
Here is the problem:
The string of 1s and 0s is 17,747,595 characters long, and it is really slowing down at around 550,000
This is the code I have:
<?php
$i=0
$len = strlen($binaryString);
while ($i < $len){
$section = substr($binaryString,$i,$i+8);
$out .= chr(bindec($section));
$i=$i+8;
}
?>
How can I make this efficient enough to run the 17 million character string?
Thanks very much for any support!
You don't need to loop you can use gmp
with pack
$file = "binary.txt";
$string = file_get_contents($file);
$start = microtime(true);
// Convert the string
$string = simpleConvert($string);
//echo $string ;
var_dump(number_format(filesize($file),2),microtime(true)- $start);
function simpleConvert($string) {
return pack('H*',gmp_strval(gmp_init($string, 2), 16));
}
Output
string '25,648,639.00' (length=13) <---- Length Grater than 17,747,595
float 1.0633520126343 <---------------- Total Conversion Time
Links
Note Solution requires GMP Functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With