title: Bit Array to String and back to Bit Array
body: <p>Possible Duplicate <a href="https://stackoverflow.com/questions/1422314/converting-byte-array-to-string-and-back-again-in-c-sharp">Converting byte array to string and back again in C#</a></p>
  
  <p>I am using Huffman Coding for compression and decompression of some text from <a href="http://snipd.net/huffman-coding-in-c" rel="nofollow noreferrer">here</a></p>
  
  <p>The code in there builds a huffman tree to use it for encoding and decoding. Everything <strong>works fine when I use the code directly</strong>.</p>
  
  <p>For my situation, i need to get the compressed content, store it and decompress it when ever need.</p>
  
  <p>The output from the encoder and the input to the decoder are <code>BitArray</code>.</p>
  
  <p>When I tried convert this <code>BitArray</code> to <code>String</code> and back to <code>BitArray</code> and decode it using the following code, I get a weird answer.</p>
  
  <pre><code>Tree huffmanTree = new Tree();
  huffmanTree.Build(input);
  
  string input = Console.ReadLine();
  BitArray encoded = huffmanTree.Encode(input);
  
  // Print the bits
  Console.Write("Encoded Bits: ");
  foreach (bool bit in encoded)
  {
      Console.Write((bit ? 1 : 0) + "");
  }
  Console.WriteLine();
  
  // Convert the bit array to bytes
  Byte[] e = new Byte[(encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1))];
  encoded.CopyTo(e, 0);
  
  // Convert the bytes to string
  string output = Encoding.UTF8.GetString(e);
  
  // Convert string back to bytes
  e = new Byte[d.Length];
  e = Encoding.UTF8.GetBytes(d);
  
  // Convert bytes back to bit array
  BitArray todecode = new BitArray(e);
  
  string decoded = huffmanTree.Decode(todecode);
  
  Console.WriteLine("Decoded: " + decoded);
  
  Console.ReadLine();
  </code></pre>
  
  <p>The Output of Original code from <a href="http://snipd.net/huffman-coding-in-c" rel="nofollow noreferrer">the tutorial</a> is:</p>
  
  <p><img src="https://i.stack.imgur.com/ZNFVX.png" alt="enter image description here"></p>
  
  <p>The Output of My Code is:</p>
  
  <p><img src="https://i.stack.imgur.com/mRwET.png" alt="enter image description here"></p>
  
  <p>Where am I wrong friends? Help me, Thanks in advance.</p>