哈夫曼编码c语言

时间: 2023-07-13 21:05:34 浏览: 50
哈夫曼编码是一种数据压缩算法,可以将原始数据压缩为更小的数据,同时保持数据的完整性。下面是一个使用C语言实现哈夫曼编码的示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_TREE_HT 100 /* 定义哈夫曼树节点结构体 */ struct node { char data; unsigned freq; struct node *left, *right; }; /* 定义哈夫曼编码结构体 */ struct code { char data; char bits[MAX_TREE_HT]; }; /* 定义哈夫曼树节点堆结构体 */ struct heap { unsigned size; unsigned capacity; struct node **array; }; /* 创建一个新的哈夫曼树节点 */ struct node* newNode(char data, unsigned freq) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->left = node->right = NULL; node->data = data; node->freq = freq; return node; } /* 创建一个新的哈夫曼树节点堆 */ struct heap* createHeap(unsigned capacity) { struct heap* heap = (struct heap*)malloc(sizeof(struct heap)); heap->size = 0; heap->capacity = capacity; heap->array = (struct node**)malloc(heap->capacity * sizeof(struct node*)); return heap; } /* 交换两个哈夫曼树节点 */ void swapNode(struct node** a, struct node** b) { struct node* t = *a; *a = *b; *b = t; } /* 维护哈夫曼树节点堆的性质 */ void heapify(struct heap* heap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < heap->size && heap->array[left]->freq < heap->array[smallest]->freq) smallest = left; if (right < heap->size && heap->array[right]->freq < heap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapNode(&heap->array[smallest], &heap->array[idx]); heapify(heap, smallest); } } /* 判断堆是否为空 */ int isHeapEmpty(struct heap* heap) { return heap->size == 0; } /* 取出堆中的最小元素 */ struct node* extractMin(struct heap* heap) { struct node* temp = heap->array[0]; heap->array[0] = heap->array[heap->size - 1]; --heap->size; heapify(heap, 0); return temp; } /* 插入一个节点到堆中 */ void insertNode(struct heap* heap, struct node* node) { ++heap->size; int i = heap->size - 1; while (i && node->freq < heap->array[(i - 1) / 2]->freq) { heap->array[i] = heap->array[(i - 1) / 2]; i = (i - 1) / 2; } heap->array[i] = node; } /* 判断是否为叶子节点 */ int isLeaf(struct node* node) { return !(node->left) && !(node->right); } /* 创建哈夫曼树 */ struct node* buildHuffmanTree(char data[], int freq[], int size) { struct node *left, *right, *top; struct heap* heap = createHeap(size); for (int i = 0; i < size; ++i) insertNode(heap, newNode(data[i], freq[i])); while (heap->size > 1) { left = extractMin(heap); right = extractMin(heap); top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertNode(heap, top); } return extractMin(heap); } /* 设置哈夫曼编码 */ void setCode(struct node* node, char code[], int top, struct code codes[]) { if (node->left) { code[top] = '0'; setCode(node->left, code, top + 1, codes); } if (node->right) { code[top] = '1'; setCode(node->right, code, top + 1, codes); } if (isLeaf(node)) { struct code c = { node->data }; strncpy(c.bits, code, top); codes[node->data] = c; } } /* 压缩数据 */ void compressData(char data[], struct code codes[], FILE *fp) { int i = 0; while (data[i]) { struct code c = codes[data[i]]; fwrite(c.bits, sizeof(char), strlen(c.bits), fp); ++i; } } /* 解压数据 */ void decompressData(struct node* root, char code[], int index, FILE *fp) { if (!root) return; if (isLeaf(root)) { printf("%c", root->data); fwrite(&root->data, sizeof(char), 1, fp); return; } index++; if (code[index] == '0') decompressData(root->left, code, index, fp); else decompressData(root->right, code, index, fp); } /* 主函数 */ int main() { char data[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(data) / sizeof(data[0]); struct node* root = buildHuffmanTree(data, freq, size); struct code codes[MAX_TREE_HT] = { 0 }; char code[MAX_TREE_HT] = { 0 }; int top = 0; setCode(root, code, top, codes); printf("Huffman Codes are:\n"); for (int i = 0; i < size; ++i) printf("%c: %s\n", data[i], codes[data[i]].bits); FILE *fp = fopen("compressed.bin", "wb"); compressData("abcdef", codes, fp); fclose(fp); fp = fopen("compressed.bin", "rb"); fseek(fp, 0L, SEEK_END); int file_size = ftell(fp); rewind(fp); char *buffer = (char*)malloc(file_size); fread(buffer, sizeof(char), file_size, fp); printf("\nCompressed data:"); for (int i = 0; i < file_size; ++i) printf("%c", buffer[i]); printf("\nDecompressed data:"); FILE *fp1 = fopen("decompressed.bin", "wb"); int index = -1; while (index < file_size - 2) decompressData(root, buffer, &index, fp1); fclose(fp1); fclose(fp); return 0; } ``` 在上面的示例中,我们定义了结构体 `node` 表示哈夫曼树节点,结构体 `code` 表示哈夫曼编码,结构体 `heap` 表示哈夫曼树节点堆。我们还定义了一些函数来操作这些结构体,如 `newNode` 创建一个新的哈夫曼树节点,`createHeap` 创建一个新的哈夫曼树节点堆,`heapify` 维护堆的性质,`extractMin` 取出堆中的最小元素等。 在主函数中,我们首先定义了一些数据和频率,然后使用 `buildHuffmanTree` 函数创建哈夫曼树。接着,我们使用 `setCode` 函数设置哈夫曼编码,并使用 `compressData` 函数压缩数据,并将压缩后的数据写入到文件中。最后,我们使用 `decompressData` 函数解压数据,并将解压后的数据写入到文件中。 这就是一个简单的哈夫曼编码的C语言实现。

相关推荐

最新推荐

recommend-type

sasasasasasasasas

sasasasasasasasas
recommend-type

VBA按模板生成表格.xlsm

VBA按模板生成表格.xlsm
recommend-type

QRBiTCN双向时间卷积神经网络分位数回归区间预测(Matlab完整源码和数据)

1.Matlab实现QRBiTCN双向时间卷积神经网络分位数回归区间预测 2.包括点预测+概率预测曲线,MatlabR2023a及以上版本运行!评价指标包括R2、MAE、RMSE、MAPE、区间覆盖率picp、区间平均宽度百分比pinaw等。 3.直接替换Excel数据即可用,注释清晰,适合新手小白,直接运行main文件一键出图。 4.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 5.适用对象:大学生课程设计、期末大作业和毕业设计。 6.作者介绍:某大厂资深算法工程师,从事Matlab、Python算法仿真工作8年;擅长智能优化算法、神经网络预测、信号处理、元胞自动机等多种领域的算法仿真实验,更多仿真源码、数据集定制私信+。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB遗传算法自动优化指南:解放算法调优,提升效率

![MATLAB遗传算法自动优化指南:解放算法调优,提升效率](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/8487939061/p208348.png) # 1. MATLAB遗传算法概述** 遗传算法是一种受生物进化启发的优化算法,它模拟了自然选择和遗传的过程。在MATLAB中,遗传算法工具箱提供了丰富的函数和类,用于创建和运行遗传算法。 **1.1 遗传算法的基本原理** 遗传算法的工作原理如下: - **初始化:**创建由随机个体组成的初始种群。 - **评估:**根据目标函数计算每个个体的适应度。 -
recommend-type

failed to register layer: ApplyLayer exit status 1 stdout: stderr: archive/tar: invalid tar header

很抱歉听到这个问题。这个错误通常是由于Docker镜像损坏或Docker存储库中缺少所需的图层引起的。您可以尝试以下几种方法来解决这个问题: 1. 清理Docker镜像和容器:使用命令“docker system prune”清理不再使用的Docker对象。 2. 检查Docker存储库:确保您正在使用可靠的Docker存储库,并检查是否存在所有必需的图层。 3. 重新下载Docker镜像:如果您确定问题是由于损坏的Docker镜像引起的,则可以尝试重新下载Docker镜像。 4. 更新Docker版本:如果您使用的是旧版Docker,则可能会出现此问题。尝试更新到最新版本的Docke
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB遗传算法大数据优化指南:应对海量数据挑战,挖掘数据价值

![MATLAB遗传算法大数据优化指南:应对海量数据挑战,挖掘数据价值](https://ask.qcloudimg.com/http-save/8934644/c34d493439acba451f8547f22d50e1b4.png) # 1. 遗传算法简介** 遗传算法(GA)是一种受进化论启发的优化算法,它模拟了生物体的自然选择和遗传过程。GA通过以下步骤迭代地搜索最优解: - **初始化:**随机生成一个种群,每个个体代表一个潜在的解决方案。 - **选择:**根据个体的适应度(目标函数值)选择适合繁殖的个体。 - **交叉:**将选定的个体配对并交换基因,产生新的个体。 - **