蘋果提供的經常使用的數據壓縮算法LZMA、ZLIB、LZ4等;算法
這三種算法也是蘋果建議的,可跨平臺使用;ui
定義以下:atom
/* Commonly-available encoders */ COMPRESSION_LZ4 = 0x100, // available starting OS X 10.11, iOS 9.0 COMPRESSION_ZLIB = 0x205, // available starting OS X 10.11, iOS 9.0 COMPRESSION_LZMA = 0x306, // available starting OS X 10.11, iOS 9.0 COMPRESSION_LZ4_RAW = 0x101, // available starting OS X 10.11, iOS 9.0 /* Apple-specific encoders */ COMPRESSION_LZFSE = 0x801, // available starting OS X 10.11, iOS 9.0
適用於有大文件數據上傳下載,節省流量能夠考慮使用;code
使用說明:blog
1. 須要引用頭文件ci
#include "compression.h"
2. 數據壓縮示例:it
- (void)testCompress{ NSData *src = [NSData dataWithContentsOfFile:@"/Users/cocoajin/Desktop/src.txt"]; NSLog(@"src: %ld",src.length); uint8_t *dstBuffer = (uint8_t *)malloc(src.length); memset(dstBuffer, 0, src.length); size_t compressResultLength = compression_encode_buffer(dstBuffer, src.length, [src bytes], src.length, NULL, COMPRESSION_LZMA); if (compressResultLength > 0) { NSData *newData = [NSData dataWithBytes:dstBuffer length:compressResultLength]; [newData writeToFile:@"/Users/cocoajin/Desktop/compress.data" atomically:YES]; NSLog(@"com: %ld",compressResultLength); NSLog(@"com: %.2f",(src.length-compressResultLength)/(float)src.length); }else{ NSLog(@"compress error!"); } free(dstBuffer); }
3. 數據解壓縮示例:io
- (void)testDeCompress{ NSData *src = [NSData dataWithContentsOfFile:@"/Users/cocoajin/Desktop/compress.data"]; NSLog(@"src: %ld",src.length); uint8_t *dstBuffer = (uint8_t *)malloc(1024*1024*10); memset(dstBuffer, 0, src.length); size_t decompressLen = compression_decode_buffer(dstBuffer,1024*1024*10,src.bytes,src.length,NULL,COMPRESSION_LZMA); if (decompressLen > 0) { NSData *newData = [NSData dataWithBytes:dstBuffer length:decompressLen]; [newData writeToFile:@"/Users/cocoajin/Desktop/decompress.txt" atomically:YES]; NSLog(@"com: %ld",decompressLen); }else{ NSLog(@"decompressLen error!"); } free(dstBuffer); }
4. 實際測對一個1.9M的txt小說文件壓縮,壓縮之後大小爲0.8m,壓縮效果仍是很明顯的;class