private static void BuildCode(string[] st, HuffmanNode x, string s) { if (x.isLeaf()) { st[x.Ch] = s; return; } BuildCode(st, x.Left, s + '0'); BuildCode(st, x.Right, s + '1'); }
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); }
public static string Expand(byte[] bytes) { int index = 0; BitArray bits = new BitArray(bytes); BitVirtualSteam bvStream = new BitVirtualSteam(bytes); HuffmanNode root = ReadTrie(bvStream, ref index); BitArray lenbs = new BitArray(32); for (int i = 0; i < 32; i++) { lenbs[i] = bits[index++]; } byte[] lenBytes = new byte[4]; lenbs.CopyTo(lenBytes, 0); //int N = BitConverter.ToInt32(lenBytes); int N = bvStream.ReadInt(); char[] chars = new char[N]; for (int i = 0; i < N; i++) { HuffmanNode x = root; while (!x.isLeaf()) { //一直往前读取 if (bvStream.ReadBoolean()) { x = x.Right; } else { x = x.Left; } } chars[i] = x.Ch; } return(string.Join("", chars)); }