可能重复 Converting byte array to string and back again in C#
我正在使用霍夫曼编码来压缩和解压缩 here 中的一些文本。
其中的代码构建了一个哈夫曼树以使用它进行编码和解码。当我直接使用代码时,一切都工作正常。
对于我的情况,我需要获取压缩内容,存储它并在需要时解压缩。
编码器的输出和解码器的输入是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();
来自the tutorial的原始代码的输出是:
我的代码的输出是:
我哪里错了 friend ?帮助我,提前致谢。
最佳答案
您不能将任意字节填充到字符串中。这个概念只是未定义。使用编码进行转换。
string output = Encoding.UTF8.GetString(e);
e
此时只是二进制垃圾,它不是 UTF8 字符串。所以对其调用UTF8方法是没有意义的。
解决方案:不要与字符串进行转换和反向转换。这不往返。你首先为什么要这样做?如果您需要字符串,请使用可往返格式,例如base-64或base-85。
关于c# - 位数组到字符串再返回位数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670645/