游程编码的原理很简单,他适用于以零开头的二进制文件的压缩,原理就是统计有多少个0,或1,将其转化为数字。 需要压缩的文件 000000000001111111111111111 00000000111111111000000000 000000000001111111111100000000 00000000000111111111111 000000000001111111111111 00000000000011111111111 需要解压的文件 11 16 8 9 9 11 11 8 11 12 11 13 12 11
class RLC
{
private:
std::ifstream *f;
public:
RLC(std::ifstream &file)
{
f = &file;
}
void expend()
{
bool b=0;
std::string str;
while (!f->eof())
{
std::getline(*f, str);
for (auto s : split(str, " "))
{
int n = std::stoi(s);
for (int i = 0; i < n; i++)
{
printf("%d",b);
}
b = !b;
}
printf("\n");
}
}
void compress()
{
std::string str;
while (!f->eof())
{
int count = 0;
std::getline(*f, str);
char c = str[0];
for (int i = 0; i < str.length(); i++)
{
if (str[i] == c)
{
count++;
}
else
{
printf("%d ", count);
c = str[i];
count = 1;
}
}
printf("%d\n",count);
}
}
};
运行结果
由于我们的c++没有split方法……所以,我从网上抄了一个,效果还不错。 转载自此处
std::vector<std::string> split(std::string str, std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str += pattern;
int size = str.size();
for (int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if (pos < size)
{
std::string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
|