C# 位数组到字节[]的转换错误

C# 位数组到字节[]的转换错误,c#,arrays,encoding,byte,bitarray,C#,Arrays,Encoding,Byte,Bitarray,我正在实施哈夫曼编码,哈夫曼算法运行良好,问题是: 当我尝试使用将BitArray转换为byte[]时 BitArray encoded = huffmanTree.Encode(input); // The encoding works well byte[] bytes = new byte[encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1 )]; encoded.CopyTo(bytes, 0); 它转换错误。我将字节数组写入一个

我正在实施哈夫曼编码,哈夫曼算法运行良好,问题是:

当我尝试使用将BitArray转换为byte[]时

BitArray encoded = huffmanTree.Encode(input); // The encoding works well
byte[] bytes = new byte[encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1 )];
encoded.CopyTo(bytes, 0);
它转换错误。我将字节数组写入一个文件,然后读取它,并再次将其转换为BitArray,以查看它是否相同:

//Displaying BitArray
        Console.Write("Encoded: ");
        foreach (bool bit in encoded)
        {
            Console.Write((bit ? 1 : 0) + "");
        }
        Console.WriteLine();

//Writing to a file
        File.WriteAllBytes(@"C:\Users\vvvoh\source\repos\Laba1Alg\Laba1Alg\Encoded", bytes);
     
// Reading from file
        byte[] bytes1 = File.ReadAllBytes(@"C:\Users\vvvoh\source\repos\Laba1Alg\Laba1Alg\Encoded");
// To BitArray
        var bits = new BitArray(bytes1);
//Displaying BitArray after reading from file
        Console.Write("Encoded again: ");
        foreach (bool bit in bits)
        {
            Console.Write((bit ? 1 : 0) + "");
        }
        Console.WriteLine();
这是输出,它显示了代码、转换前和转换后的位数组

Origin: ABC
Code:
A - 10
B - 11
C - 0
Encoded: 10110
Encoded again: 10110000
Final: ABCCCC

请让我知道我的错误在哪里,帮助我理解我的错误在哪里。

您不能保存少于8位的数据。你必须分别存储你实际拥有的位数信息,否则就无法知道8位中有多少位在使用。我该怎么做?除了实际数据之外,还要写一个数字,说明文件中有多少位