范式huffman解码 c语言
时间: 2023-11-30 07:01:05 浏览: 88
用C语言实现的Huffman编解码程序
3星 · 编辑精心推荐
要解码Huffman编码,需要构建Huffman树,然后根据树的结构进行解码。下面是C语言实现的范例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义Huffman树的结点
typedef struct Node {
unsigned char data; // 字符
int frequency; // 字符频率
struct Node* left; // 左子树
struct Node* right; // 右子树
} Node;
// 创建Huffman树的结点
Node* createNode(unsigned char data, int frequency) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->frequency = frequency;
newNode->left = newNode->right = NULL;
return newNode;
}
// 构建Huffman树
Node* buildHuffmanTree(unsigned char* data, int* frequency, int size) {
int i, j;
// 初始化结点数组
Node** nodes = (Node**)malloc(size * sizeof(Node*));
for (i = 0; i < size; i++) {
nodes[i] = createNode(data[i], frequency[i]);
}
// 构建树
while (size > 1) {
// 找出最小和次小的结点
int min1 = 0, min2 = 1;
if (frequency[min1] > frequency[min2]) {
int temp = min1;
min1 = min2;
min2 = temp;
}
for (i = 2; i < size; i++) {
if (frequency[i] < frequency[min1]) {
min2 = min1;
min1 = i;
}
else if (frequency[i] < frequency[min2]) {
min2 = i;
}
}
// 创建新的父结点
Node* parent = createNode('\0', frequency[min1] + frequency[min2]);
parent->left = nodes[min1];
parent->right = nodes[min2];
// 将父结点插入数组
nodes[min1] = parent;
// 删除次小的结点
for (j = min2; j < size - 1; j++) {
nodes[j] = nodes[j + 1];
frequency[j] = frequency[j + 1];
}
size--;
}
// 返回根结点
return nodes[0];
}
// Huffman解码
void decodeHuffman(Node* root, unsigned char* encodedData, int size) {
Node* current = root;
for (int i = 0; i < size; i++) {
if (encodedData[i] == '0') {
current = current->left;
} else {
current = current->right;
}
// 到达叶子结点,输出字符
if (current->left == NULL && current->right == NULL) {
printf("%c", current->data);
current = root;
}
}
}
int main() {
unsigned char data[] = {'A', 'B', 'C', 'D', 'E'};
int frequency[] = {5, 3, 6, 2, 4};
int size = sizeof(data) / sizeof(data[0]);
Node* root = buildHuffmanTree(data, frequency, size);
unsigned char encodedData[] = "100010101011";
int encodedSize = sizeof(encodedData) / sizeof(encodedData[0]) - 1;
decodeHuffman(root, encodedData, encodedSize);
return 0;
}
```
范例代码中,首先定义了Huffman树的结点和相应的操作函数。然后,通过构建Huffman树实现了解码函数decodeHuffman。在主函数中,定义了字符数据data和频率frequency,根据这些数据创建Huffman树的根结点root。接下来,定义了编码数据encodedData,并调用decodeHuffman函数对编码数据进行解码。输出结果为解码后的字符。
阅读全文