在我们嵌入式开发中,通信中有些数据量较大的数据可以压缩之后再进行传输。
压缩算法有很多,常用的有如下几种:
本次来介绍压缩界的速度之王——lz4压缩库。一些数据如:
lz4源码下载链接:
http://security.ubuntu.com/ubuntu/pool/main/l/lz4/
首先,从上面的链接中下载源码进行编译:
然后在源码根目录创建一个文件夹lz4_x86_lib:
编译lz4:
make
make install PREFIX=$(pwd)/lz4_x86_lib
得到:
lz4库交叉编译可参照:https://www.cdsy.xyz/computer/programme/Other/240726/cd62368.html
lz4库有几套压缩、解压接口,我们使用最简单的接口:
int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize);
int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
测试例子:
把字符串"12345678901234567890123456789012345678901234567890"进行lz4压缩,再解压,再把解压之后的内容打印出来。
编写测试代码:
// 微信公众号:嵌入式大杂烩
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "lz4.h"
long long get_sys_time_us(void)
{
long long time_us = 0;
struct timeval sys_current_time;
gettimeofday(&sys_current_time, NULL);
time_us = (long long)sys_current_time.tv_sec*1000000 + sys_current_time.tv_usec;
return time_us;
}
int main(int arc, char *argv[])
{
// 压缩
char *src0 = "12345678901234567890123456789012345678901234567890";
char dst0[64] = {0};
int src0_size = strlen(src0) + 1;
int max_dst0_size = sizeof(dst0);
int dst0_compress_size = 0;
printf("before compress = %s, bytes = %d\n", src0, src0_size);
if (src0_size < max_dst0_size)
{
long long compress_start_time = get_sys_time_us();
dst0_compress_size = LZ4_compress_default(src0, dst0, src0_size, max_dst0_size);
long long compress_end_time = get_sys_time_us();
printf("after compress = %s\n", dst0);
printf("compress_time = %lld us\n", compress_end_time - compress_start_time);
}
else
{
printf("compress error! src0_size >= max_dst0_size\n");
}
// 解压
char src1[64] = {0};
char dst1[64] = {0};
int compressed_size = dst0_compress_size;
int max_decompressed_size = sizeof(dst1);
int dst1_decompress_size = 0;
if (dst0_compress_size < max_decompressed_size)
{
memcpy(src1, dst0, dst0_compress_size);
printf("before decompress = %s\n", src1);
}
else
{
printf("dst0_compress_size >= max_decompressed_size\n");
}
if (compressed_size < max_decompressed_size)
{
long long decompress_start_time = get_sys_time_us();
dst1_decompress_size = LZ4_decompress_safe(src1, dst1, compressed_size, max_decompressed_size);
long long decompress_end_time = get_sys_time_us();
printf("after decompress = %s, bytes = %d\n", dst1, dst1_decompress_size);
printf("decompress_time = %lld us\n", decompress_end_time - decompress_start_time);
}
else
{
printf("decompress error! compressed_size >= max_decompressed_size\n");
}
return 0;
}
编译运行:
gcc -o lz4_test lz4_test.c -Llz4_x86_lib/lib -Ilz4_x86_lib/include -llz4
./lz4_test
更多实例可参照源码路径下的examples。