public string decode(BitArray bits) { Node current = this.Root; string decoded = ""; foreach (bool bit in bits) { if (bit) { if (current.Right != null) { current = current.Right; } } else { if (current.Left != null) { current = current.Left; } } if (IsLeaf(current)) { decoded += current.Symbol; //save row into table bool existed = false; //check if current symbol exist in table foreach (row reference in table) { if (Convert.ToString(current.Symbol) == reference.symbol) { existed = true; } } if (!existed) { row row = new row(); row.symbol += current.Symbol; row.codeword = ""; row.frequency = current.Frequency; List <bool> codeword = this.Root.Traverse(current.Symbol, new List <bool>()); foreach (bool char_bit in codeword) { row.codeword += (char_bit ? 1 : 0) + ""; } table.Add(row); } //reset current node current = this.Root; } } return(decoded); }
public void create_table() { foreach (KeyValuePair <char, int> pair in Frequencies) { row row = new row(); Node node = this.Root; row.symbol += pair.Key; row.frequency = pair.Value; List <bool> codeword = node.Traverse(pair.Key, new List <bool>()); foreach (bool char_bit in codeword) { row.codeword += (char_bit ? 1 : 0) + ""; } table.Add(row); } }
public BitArray encode(string source) { List <bool> encodedSource = new List <bool>(); for (int i = 0; i < source.Length; i++) { List <bool> codeword = this.Root.Traverse(source[i], new List <bool>()); encodedSource.AddRange(codeword); bool existed = false; string symbol = ""; symbol += source[i]; // check if current symbol existed in the table foreach (row reference in table) { if (symbol == reference.symbol) { existed = true; } } //if current row doesn't exist in the table, add it if (!existed) { row row = new row(); row.symbol = symbol; Frequencies.TryGetValue(source[i], out row.frequency); row.codeword = ""; foreach (bool char_bit in codeword) { row.codeword += (char_bit ? 1 : 0) + ""; } table.Add(row); } } BitArray bits = new BitArray(encodedSource.ToArray()); return(bits); }