private static void WriteTrie(BitVirtualSteam bvStream, HuffmanNode x) { if (x.isLeaf()) { bvStream.Write(true); bvStream.Write(x.Ch); return; } bvStream.Write(false); WriteTrie(bvStream, x.Left); WriteTrie(bvStream, x.Right); }
// 返回bytes public static byte[] Compress(string text) { BitVirtualSteam bvStream = new BitVirtualSteam(); char[] chars = text.ToCharArray(); // 统计频次 int[] freqs = new int[R]; for (int i = 0; i < chars.Length; i++) { freqs[chars[i]]++; } HuffmanNode root = BuildTrie(freqs); // 构造编译表 每个字母 对应一个 code 字符串 string[] st = new string[R]; BuildCode(st, root, ""); List <bool> bits = new List <bool>(); WriteTrie(bvStream, root); bvStream.Write(text.Length); // var lenBytes = BitConverter.GetBytes(text.Length); // BitArray array = new BitArray(lenBytes); // for (int i = 0; i < array.Length; i++) // { // bits.Add(array[i]); // } for (int i = 0; i < text.Length; i++) { string code = st[text[i]]; for (int j = 0; j < code.Length; j++) { if (code[j] == '1') { bvStream.Write(true); } else { bvStream.Write(false); } } } return(bvStream.GetBytes()); }
static void Main(string[] args) { BitVirtualSteam bvStream = new BitVirtualSteam(); // 12 bit (0,4096) bvStream.Write(4095, 12); int v = bvStream.ReadInt(12); var bytes = HuffmanTrie.Compress("ABRACADABRA!"); string str = HuffmanTrie.Expand(bytes); //HuffmanTrie.Compress("it was the best of times it was the worst of times !"); byte[] lzwBytes = LZW.Compress("ABRACADABRABRABRA"); string lzwText = LZW.Expand(lzwBytes); Console.WriteLine("Hello World!"); }