压缩\解压缩二进制文件



我需要将 *.bin 文件解压缩为某个临时文件,在我的程序中使用它执行某些操作,然后压缩它。有一个函数可以解压缩 *.bin 文件。即,获得程序正确操作的临时文件。功能:

public void Unzlib_bin(string initial_location, string target_location)
{
byte[] data, new_data;
Inflater inflater;
inflater = new Inflater(false);
data = File.ReadAllBytes(initial_location);
inflater.SetInput(data, 16, BitConverter.ToInt32(data, 8));
new_data = new byte[BitConverter.ToInt32(data, 12)];
inflater.Inflate(new_data);
File.WriteAllBytes(target_location, new_data);
}

问题是如何将临时文件打包到其原始状态?我正在尝试执行以下操作,但结果是错误的:

public void Zlib_bin(byte[] data, int length, string target_location)
{
byte[] new_data;
Deflater deflater;
List<byte> compress_data;
compress_data = new List<byte>();
new_data = new byte[length];
deflater = new Deflater();
compress_data.AddRange(new byte[] { ... }); //8 bytes from header, it does not matter
deflater.SetLevel(Deflater.BEST_COMPRESSION);
deflater.SetInput(data, 0, data.Length);
deflater.Finish();
deflater.Deflate(new_data);
compress_data.AddRange(BitConverter.GetBytes(new_data.Length));
compress_data.AddRange(BitConverter.GetBytes(data.Length));
compress_data.AddRange(new_data);
File.WriteAllBytes(target_location, compress_data.ToArray());
}

有什么想法吗?

如果"结果是错误的",则表示无法压缩回完全相同的字节,这完全是意料之中的。不能保证解压缩后压缩会给你同样的东西,除非你使用完全相同的压缩代码、该代码的版本以及该代码的设置。

有许多压缩数据流来表示相同的未压缩数据,压缩器可以自由使用其中任何一个,通常是由于执行时间、使用的内存和压缩比率的权衡。这就是为什么压缩机具有"液位"和其他调整的原因。

无损压缩器的唯一保证是,当您压缩然后解压缩时,您会得到完全开始的内容。

如果解压缩您得到的内容提供了相同的未压缩数据,那么一切都很好。

最新更新