我有LZW的压缩器/解压缩器。 现在我想使用自定义变量( size )来保持字节大小以字节为单位然后变得足够大我将字典恢复到初始状态并开始再次填充它。
但我没有意识到如何实现它。我有几次尝试。
编码器
void lzwCodeFile(istream &in, ostream &out, uint32_t maxSize) {
unordered_map<string, uint32_t> mp;
clearAndFill(mp);
uint32_t code = 256;
uint32_t size = 256;
string w = "";
string tmp;
uint8_t c;
while (in.read((char *) &c, sizeof c)) {
tmp = w;
tmp += c;
if (mp.find(tmp) != mp.end()) {
w = tmp;
} else {
uint32_t val = mp[w];
out.write((const char *) &val, sizeof(mp[w]));
//cout << val << " ";
mp[tmp] = code++;
size += tmp.size();
w = c;
}
}
if (w.size()) {
uint32_t val = mp[w];
out.write((const char *) &val, sizeof(mp[w]));
//cout << val << " ";
}
}
解码器
void lzwDecodeFile(istream &in, ostream &out, uint32_t maxSize) {
unordered_map<uint32_t, string> mp;
uint32_t code = 256;
uint32_t size = 256;
clearAndFillRev(mp);
string tmp, w;
uint32_t k;
in.read((char *) &k, sizeof k);
w = "" + mp[k];
string entry;
out << w;
while (in.read((char *) &k, sizeof k)) {
// finded
if (mp.find(k) != mp.end()) {
entry = mp[k];
} else {
entry = w + w[0];
}
out << entry;
tmp = w + entry[0];
mp[code++]=tmp;
w = entry;
}
}