2013-06-25 51 views
0

我完成了我的Huffman壓縮/解壓縮算法。我使用一個字符串來檢查我的輸入,例如「foo bar」7x8 = 56給我10010110111011100 = 17 + - 從原始大小壓縮回來的35%。保存huffman壓縮文件/字符串

但現在我想將它保存爲一個文件,任何人都可以向我解釋如何做到這一點。

如果需要,我可以發佈我的應用程序的來源。

我的形式只是一個 碼(也有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文件中以便稍後解碼文件。

希望這可以清除它。

回答

0

您可能需要一個Base64編碼器(失去壓縮),使其預覽,能夠在文本編輯器,保存它,那麼你只需要輸出到一個文件

System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", str_your_base64_encoded_bit_array); 

或直接(因爲它是一個壓縮文件):

BitArray bit_array = . . . . 
byte [] bytes = new byte[bit_array.Length/8 + (bit_array.Length % 8 == 0 ? 0 : 1)]; 
bit_array.CopyTo(bytes, 0); 
File.WriteAllBytes(@"C:\MyFile.bin", bytes); 
+0

是的,這正是我需要的,非常感謝你的幫助! – user2519968