为何gz文件出现负压缩比?实际正确压缩比应为87.2%
gzip文件显示负压缩比的原因分析
问题现象
使用gzip 1.5版本的gzip -l命令查看dns-query.log-2022083103.gz时,得到的未压缩文件大小为679547787字节,压缩比显示为-74.7%;但实际解压后,文件大小为9269482379字节,计算得出的正确压缩比应为87.2%。而另一个较小的gz文件dns-security.log-2022083103.gz,gzip -l显示的压缩比与实际计算结果完全一致。
相关操作命令及结果:
[root@pridns named]# ll dns-query.log-2022083103* -rw-r--r-- 1 named named 1.2G Aug 31 03:10 dns-query.log-2022083103.gz [root@pridns named]# gzip -l dns-query.log-2022083103.gz compressed uncompressed ratio uncompressed_name 1187103824 679547787 -74.7% dns-query.log-2022083103 [root@pridns named]# gunzip -c dns-query.log-2022083103.gz > dns-query.log-2022083103 [root@pridns named]# ls -l dns-query.log-2022083103* -rw-r--r-- 1 root root 9269482379 Sep 16 11:06 dns-query.log-2022083103 -rw-r--r-- 1 named named 1187103824 Aug 31 03:10 dns-query.log-2022083103.gz [root@pridns named]# gzip --version gzip 1.5 Copyright (C) 2007, 2010, 2011 Free Software Foundation, Inc. Copyright (C) 1993 Jean-loup Gailly. This is free software. You may redistribute copies of it under the terms of the GNU General Public License <http://www.gnu.org/licenses/gpl.html>. There is NO WARRANTY, to the extent permitted by law. Written by Jean-loup Gailly.
测试正常文件的操作结果:
[root@pridns named]# gzip -l dns-security.log-2022083103.gz compressed uncompressed ratio uncompressed_name 131503235 1275215408 89.7% dns-security.log-2022083103 [root@pridns named]# zcat dns-security.log-2022083103.gz > dns-security.log-2022083103 [root@pridns named]# ls -l dns-security.log-2022083103* -rw-r--r-- 1 root root 1275215408 Sep 16 11:31 dns-security.log-2022083103 -rw-r--r-- 1 named named 131503235 Aug 31 03:10 dns-security.log-2022083103.gz
根本原因
gzip格式的文件头中,存储原始未压缩文件大小的字段是一个32位无符号整数,它的最大值为2^32 - 1(即4294967295字节,约4GB)。当原始文件大小超过这个数值时,该字段会发生溢出,最终存储的是原始大小对2^32取模后的结果。
在你的案例中,原始文件大小为9269482379字节,计算取模结果:
9269482379 % 4294967296 = 9269482379 - 2*4294967296 = 679547787
这个数值正好是gzip -l显示的未压缩大小。gzip用这个错误的数值计算压缩比,自然得出了不合理的负比值。
而另一个正常文件的原始大小为1275215408字节,小于4GB,所以文件头中的大小字段准确,压缩比计算也正常。
补充说明
gzip 1.5版本没有针对超大文件的这个问题做适配,后续的gzip 1.6及以上版本已经优化了对超过4GB文件的大小识别逻辑,能正确显示原始文件大小和压缩比。
内容的提问来源于stack exchange,提问作者Donghua Liu
相关产品推荐
相关产品推荐

