gpt4 book ai didi

PHP LZW二进制解压函数

转载 作者:可可西里 更新时间:2023-11-01 12:38:20 24 4
gpt4 key购买 nike

我一直在 Internet 上查找,但在 PHP 中找不到可处理这些 javascript 函数输出的数据的 LZW 解压缩实现:

function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}

function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
debugger;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}

我真的只需要一个 PHP 中的解压缩算法,它可以与上面的压缩 javascript 函数一起使用。

上面的 lzw_encode 函数将“This is a test of the compression function”编码为“This Ă a test ofĈhe comprĊsion functěn”

我发现的库要么有问题 (http://code.google.com/p/php-lzw/),要么不接受 UTC 字符的输入。

如有任何帮助,我们将不胜感激

谢谢!

最佳答案

我已经为您将它移植到 PHP 并对其进行了测试:

function lzw_decode($s) {
mb_internal_encoding('UTF-8');

$dict = array();
$currChar = mb_substr($s, 0, 1);
$oldPhrase = $currChar;
$out = array($currChar);
$code = 256;
$phrase = '';

for ($i=1; $i < mb_strlen($s); $i++) {
$currCode = implode(unpack('N*', str_pad(iconv('UTF-8', 'UTF-16BE', mb_substr($s, $i, 1)), 4, "\x00", STR_PAD_LEFT)));
if($currCode < 256) {
$phrase = mb_substr($s, $i, 1);
} else {
$phrase = $dict[$currCode] ? $dict[$currCode] : ($oldPhrase.$currChar);
}
$out[] = $phrase;
$currChar = mb_substr($phrase, 0, 1);
$dict[$code] = $oldPhrase.$currChar;
$code++;
$oldPhrase = $phrase;
}
var_dump($dict);
return(implode($out));
}

关于PHP LZW二进制解压函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10342963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com