1. 程式人生 > >【神經網路與深度學習】【C/C++】ZLIB學習

【神經網路與深度學習】【C/C++】ZLIB學習

zlib(http://zlib.NET/)提供了簡潔高效的In-Memory資料壓縮和解壓縮系列API函式,很多應用都會用到這個庫,其中compress和uncompress函式是最基本也是最常用的。不過很奇怪的是,compress和uncompress函式儘管已經非常的簡單,卻仍然有不少人用得不好,其實歸根結底還是在於有些事情沒有弄明白,這裡大家先看下面的程式碼

#include <stdlib.h>  
#include <string.h>  
#include <stdio.h>  
#include <zlib.h>  
  
int main(int argc, char* argv[])  
{  
    char text[] = "zlib compress and uncompress test\

[email protected]\n2012-11-05\n";  
    uLong tlen = strlen(text) + 1;  /* 需要把字串的結束符'\0'也一併處理 */  
    char* buf = NULL;  
    uLong blen;  
  
    /* 計算緩衝區大小,併為其分配記憶體 */  
    blen = compressBound(tlen); /* 壓縮後的長度是不會超過blen的 */  
    if((buf = (char*)malloc(sizeof(char) * blen)) == NULL)  
    {  
        printf("no enough memory!\n");  
        return -1;  
    }  
  
    /* 壓縮 */  
    if(compress(buf, &blen, text, tlen) != Z_OK)  
    {  
        printf("compress failed!\n");  
        return -1;  
    }  
  
    /* 解壓縮 */  
    if(uncompress(text, &tlen, buf, blen) != Z_OK)  
    {  
        printf("uncompress failed!\n");  
        return -1;  
    }  
  
    /* 列印結果,並釋放記憶體 */  
    printf("%s", text);  
    if(buf != NULL)  
    {  
        free(buf);  
        buf = NULL;  
    }  
  
    return 0;  
}  

zlib處理的物件是Bytef*位元組流,很多人遇到字串就會混淆了,其實很簡單,位元組流是沒有結束符的,需要配備長度資訊,所以處理字串的時候需要把結束符也當成一個普通的位元組,這樣計算長度的時候也需要算它一份。另外絕大部分人都想動態分配緩衝區,也就是說需要多少再給多少,其實zlib本身有提供compressBound函式用於計算壓縮後緩衝區長度的上限值,不需要額外再設計一些不適當的預測演算法,不過解壓縮的時候沒有提供長度的預測,由於compress和uncompress一般都是成對使用的,預先儲存好原文的長度即可。