【发布时间】:2013-06-25 15:22:08
【问题描述】:
我已经完成了我的 Huffman 压缩/解压缩算法。我使用一个字符串来检查我的输入,比如 "foo bar" 7x8 = 56 给了我 10010110111011100 = 17 +- 35% 从原始大小压缩回来。
但是现在我想将其保存为文件,谁能解释一下如何做到这一点。
如果需要,我可以发布我的应用程序的源代码。
我的表单只是一个 代码(也有用于遍历树的 cNode 类)
class cZU
{
private List<cNode> cNodes = new List<cNode>();
public cNode Root { get; set; }
public Dictionary<char, int> Frequencies = new Dictionary<char, int>();
public void mWalktree(string source)
{
for (int i = 0; i < source.Length; i++)
{
if (!Frequencies.ContainsKey(source[i]))
{
Frequencies.Add(source[i], 0);
}
Frequencies[source[i]]++;
}
foreach (KeyValuePair<char, int> symbol in Frequencies)
{
cNodes.Add(new cNode() { Symbol = symbol.Key, Frequency = symbol.Value });
}
while (cNodes.Count > 1)
{
List<cNode> orderedcNodes = cNodes.OrderBy(cNode => cNode.Frequency).ToList<cNode>();
if (orderedcNodes.Count >= 2)
{
// Take first two items
List<cNode> taken = orderedcNodes.Take(2).ToList<cNode>();
// Create a parent cNode by combining the frequencies
cNode parent = new cNode()
{
Symbol = '*',
Frequency = taken[0].Frequency + taken[1].Frequency,
Left = taken[0],
Right = taken[1]
};
cNodes.Remove(taken[0]);
cNodes.Remove(taken[1]);
cNodes.Add(parent);
}
this.Root = cNodes.FirstOrDefault();
}
}
public BitArray Encode(string source)
{
List<bool> encodedSource = new List<bool>();
for (int i = 0; i < source.Length; i++)
{
List<bool> encodedSymbol = this.Root.Traverse(source[i], new List<bool>());
encodedSource.AddRange(encodedSymbol);
}
BitArray bits = new BitArray(encodedSource.ToArray());
return bits;
}
现在我只是这样做:
string = "foo bar";
ZU.mWalktree(inputstring);
只是将编码的字符串输出给用户,但我需要将编码的文件保存到 .txt,我的问题是我需要在该 .txt 文件中保存什么以便稍后解码文件。
希望这可以清除它。
【问题讨论】:
标签: c# huffman-code