DEFLATED数据将始终大于未压缩的输入数据

时间:2017-06-17 10:30:44

标签: c++ zlib

我现在正试图了解deflate和 inflate 的工作方式 这是一个带有 dummyFields 结构的简单程序。

// Here i give a total memory size for the output buffer used by deflate func
#define CHUNK 16384

struct dummyFields
{
    long a;
    char b;
    long c;
    float d;
    float e;
    float f;
    float g;
    float h;
    char i;
    unsigned int j;
};

Bytef *dataOriginal = (Bytef*)malloc( sizeof(dummyFields) );
Bytef *dataCompressed = (Bytef*)malloc( CHUNK );

z_stream s
s.zalloc = Z_NULL;
s.zfree = Z_NULL;
s.opaque = Z_NULL;
deflateInit(&s, Z_DEFAULT_COMPRESSION);

s.avail_out = CHUNK;
s.next_out = dataCompressed;

int compressSize = 0;
int decompSize = 0;
dummyFields para;

    // set all values equals to 0
    memset( &para, 0, sizeof(dummyFields) );
    //Inserts value in struct fields
    para.a = 31272;
    para.b = 'z';
    para.c = 66.54;
    para.e = 123;
    para.f = 66.54;
    .
    .
    para.j = 123;
    //copy this values in a Bytef* elements
    memcpy( dataOriginal, &para, sizeof(dummyFields));

    s.avail_in = sizeof(dummyFields);
    s.next_in = dataOriginal;

    int response = deflate(&s, Z_FINISH);

    //don't get any errors here
    if( res == Z_STREAM_END ){
        compressSize = CHUNK - s.avail_out;
    }
}
deflateEnd(&s);

//here I get 45 byte but actual struct sizeof is 40.
printf("Total bytes after compress %d\n",compressSize); 

// Trying to get back my data
Bytef *decomp = (Bytef*)malloc( sizeof(Particle) );

z_stream s_inflate;
s_inflate.zalloc = Z_NULL;
s_inflate.zfree = Z_NULL;
s_inflate.opaque = Z_NULL;
inflateInit(&s_inflate);

// data i want to get at the next inflate
s_inflate.avail_in = spaceUsed;
s_inflate.next_in = dataCompressed;

s_inflate.avail_out = sizeof(dummyFields);
s_inflate.next_out = decomp;

int response = inflate( &s_inflate, Z_NO_FLUSH );

if( res == Z_STREAM_END ){
        decompSize = CHUNK - s.avail_out;
}
//Here I got 40 bytes which is correct beacuse actual struct size is 40
printf("Total bytes after compress %d\n",decompSize);
inflateEnd( &s_inflate );

dummyFields data;
memset( &data, 0, sizeof(data) );
memcpy( &data, decomp, sizeof(data));

当我试图从膨胀响应中支持我的数据时,我得到了实际值(这是正确的)。 Deflate和Inflate功能正常工作。

当我试图找到(sizeof(dummyFields))结构的大小时,它给我40个字节

问题

  • 当我压缩它给我45的数据时,struct的实际大小是40 字节怎么可能?

  • 我的需求数据是30到40个字节是否有任何其他库 将数据压缩10到20个字节(当我给30到40个字节时)?

  • 输出压缩数据是否有某种方式可以保证 比输入数据更小?

注意

当我增加结构字段数或数据大小40到100字节时,压缩结果为OK。 当我减少字段数或大小100字节到40字节时压缩结果不好

1 个答案:

答案 0 :(得分:3)

没有保证输出压缩数据将是SMALLER。压缩意味着存储一些开销,用于存储描述被打包数据的一些结构信息(如原始情况下的字典),允许使用更少的空间来表示数据。对于单个压缩结构,您可能会获得更大的压缩输出,但是对于这些结构的数组,您很可能会获得更小的压缩输出(特别是当它们彼此之间没有很大差异时)。

如果您的压缩输出结果大于未压缩的输出,则只存储未压缩的版本。