简体   繁体   English

PHP将二进制字符串转换为二进制的高效方法

[英]PHP Efficient way to Convert String of Binary into Binary

here is the skinny (scroll down to see the problem): I am doing Huffman Encoding to compress a file using PHP (for a project). 这是瘦的(向下滚动以查看问题):我正在使用Huffman Encoding来压缩文件(对于一个项目)。 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. 现在,我需要将其转换为实际的二进制字符串,在当前状态下,它只是一个1和0的字符串。

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 1s和0s的字符串长度为17,747,595个字符,它实际上正在减速到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? 如何才能使这个效率足以运行1700万个字符串?

Thanks very much for any support! 非常感谢您的支持!

You don't need to loop you can use gmp with pack 你不需要循环你可以使用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 注意解决方案需要GMP功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM