我正在使用以下方法实现游程长度编码GZipStream
C# winforms 应用程序中的类。
数据以一系列由换行符分隔的字符串形式提供,如下所示:
FFFFFFFF
FFFFFEFF
FDFFFFFF
00FFFFFF
在压缩之前,我将字符串转换为字节数组,但如果存在换行符,则这样做会失败。
每个换行符都很重要,但我不确定如何保留它们在编码中的位置。
这是我用来转换为字节数组的代码:
private static byte[] HexStringToByteArray(string _hex)
{
_hex = _hex.Replace("\r\n", "");
if (_hex.Length % 2 != 0) throw new FormatException("Hex string length must be divisible by 2.");
int l = _hex.Length / 2;
byte[] b = new byte[l];
for (int i = 0; i < l; i++)
b[i] = Convert.ToByte(_hex.Substring(i * 2, 2), 16);
return b;
}
Convert.ToByte
如果未删除换行符,则抛出 FormatException,并显示以下信息:“其他不可解析的字符位于字符串末尾。”这并不令我惊讶。
确保正确包含换行符的最佳方法是什么?
Note我应该补充一点压缩的该字符串的版本本身必须是可以包含在 XML 文档中的字符串。
Edit:
我尝试简单地将字符串转换为字节数组,而不对其执行任何二进制转换,但在压缩方面仍然遇到问题。以下是相关方法:
private static byte[] StringToByteArray(string _s)
{
Encoding enc = Encoding.ASCII;
return enc.GetBytes(_s);
}
public static byte[] Compress(byte[] buffer)
{
MemoryStream ms = new MemoryStream();
GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
zip.Write(buffer, 0, buffer.Length);
zip.Close();
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return gzBuffer;
}