【发布时间】:2013-01-18 04:51:37
【问题描述】:
可能重复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 的原始代码输出为:
我的代码的输出是:
朋友们我哪里错了?帮助我,在此先感谢。
【问题讨论】:
-
请记住,C# 字符串是 UTF-16。
-
我用同样奇怪的答案尝试了 ASCII。我尝试了 Unicode (UTF-16),但给出了一半正确和一半垃圾的答案。喜欢
Welcome给WelcomESTT -
问题是
CopyTo假定 LSB 优先,而世界上其他所有健全的 API 都使用 MSB 优先。因此10000000b等于1而不是128
标签: c# string bytearray bitarray huffman-code