PHP Efficient way to convert binary string to binary

Here is a skinny one (scroll down to see the problem): I am doing Huffman encoding to compress a file using PHP (for a project). I made a map and did everything in a line like:

00101010001100001110011101001101111011111011 

Now I need to convert this to the actual binary string in the current state, this is just a string of 1s and 0s.

Here is the problem :

A line of 1s and 0s is 17,747,595 characters, and it really slows down by about 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 it efficient enough to run a 17mm character string?

Thanks so much for any support!

+6
source share
1 answer

You do not 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)); } 

Exit

 string '25,648,639.00' (length=13) <---- Length Grater than 17,747,595 float 1.0633520126343 <---------------- Total Conversion Time 

References

Note. Solution requires GMP Function

+5
source

All Articles