C#でバイト配列を文字列に変換し、再び元に戻す可能性のある重複
ここからいくつかのテキストの圧縮と解凍にハフマンコーディングを使用しています
そこにあるコードは、エンコードとデコードに使用するハフマン ツリーを構築します。コードを直接使用すると、すべて正常に動作します。
私の状況では、圧縮されたコンテンツを取得して保存し、必要に応じて解凍する必要があります。
エンコーダからの出力とデコーダへの入力はBitArray
です。
BitArray
次のコードを使用してこれを変換しString
て元に戻しBitArray
、デコードしようとすると、奇妙な答えが得られます。
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();
チュートリアルからの元のコードの出力は次のとおりです。
私のコードの出力は次のとおりです。
私はどこで間違った友達ですか?助けてください、よろしくお願いします。