基于C语言的Huffman解压缩函数故障排查求助
Huffman解压缩函数返回空字符串排查
我正在开发一个C语言程序,用于对参数传入的Huffman压缩文件进行解压缩,但解压缩函数无法正常工作,返回空字符串,请求协助排查问题。
压缩格式示例
110;;1100;o1101000; 1101001;f1101010;r1101011; 1101100;�1101101;�1101110;{1101111;�1110000;�1110001;�1110010;�1110011;@1110100;61110101;m11101100;h11101101;l11101110;e11101111;01111; ���;o�;�����E}�j�U����͛wo�Ǘ>�@6
解压缩函数代码
我已实现文件读取和Huffman编码头部解析函数,以下是存在问题的解压缩函数:
unsigned char *read_bits_from_compressed(unsigned char *str, list_t *code) { int str_len = strlen(str); unsigned char padding = str[str_len - 1]; int padding_bits = padding >> 4; int bits_read = 0; int curr_byte = 0; int curr_bit = 7; int bit = 0; int i = 0; int j = 0; node_t *node = code->head; cipher_t *cipher = NULL; unsigned char *result = malloc(str_len); memset(result, 0, str_len); for (i = str_len - 2; i >= 0; i--) { curr_byte = str[i]; for (j = 7; j >= 0; j--) { bit = (curr_byte >> j) & 1; while (node != NULL && bits_read < padding_bits) { node = node->next; bits_read++; } while (node != NULL) { cipher = (cipher_t *) node->data; if (cipher->code[curr_bit] == bit) { curr_bit--; if (cipher->code[curr_bit + 1] == -1) { result[str_len - padding - 1 - i] = cipher->c; node = code->head; curr_bit = 7; break; } } else { node = node->next; curr_bit = 7; } } } } return result; }
函数预期执行步骤
- 从末尾倒序读取字符串
- 获取字符串末尾的填充位值(注:代码逻辑取末尾字符,与原描述“首字符为填充位”存在矛盾)
- 逐位读取数据并忽略填充位
- 将完整比特序列存入数组
- 匹配比特序列对应的字符
- 将字符写入输出结果
- 重复操作至压缩数据末尾(需跳过Huffman编码头部)
所用链表及数据结构
链表定义
typedef struct list { node_t *head; node_t *tail; size_t size; } list_t;
节点定义
typedef struct node { struct node *prev; struct node *next; void *data; } node_t;
节点存储的 cipher 结构
typedef struct cipher { unsigned char c; int *code; } cipher_t;
其中c对应字符,code对应Huffman编码(由0和1组成,以-1结尾)。
内容的提问来源于stack exchange,提问作者Nayrosk
相关产品推荐
相关产品推荐

