用C写一个算术编码解码
时间: 2023-05-19 07:03:27 浏览: 96
用C语言实现算术编码(C语言).doc
算术编码是一种无损数据压缩算法,可以将任意长度的数据压缩成一个小数。解码时,根据压缩时使用的概率分布,将小数还原成原始数据。以下是用C语言实现算术编码解码的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1000
typedef struct {
int low;
int high;
int range;
} Range;
void encode(char* input, char* output) {
int freq[256] = {0};
int len = strlen(input);
for (int i = 0; i < len; i++) {
freq[input[i]]++;
}
int total = 0;
for (int i = 0; i < 256; i++) {
total += freq[i];
}
for (int i = 0; i < 256; i++) {
freq[i] = (freq[i] * 10000) / total;
}
Range r = {0, 9999, 10000};
int low = 0;
int high = 9999;
for (int i = 0; i < len; i++) {
int c = input[i];
int new_low = low + (r.range * freq[c]) / 10000;
int new_high = low + (r.range * freq[c+1]) / 10000 - 1;
r.low = new_low;
r.high = new_high;
while (1) {
if (r.low / 1000 == r.high / 1000) {
int digit = r.low / 1000;
output[i] = digit;
low -= digit * r.range / 10000;
high -= digit * r.range / 10000;
r.low = (r.low % 1000) * 10;
r.high = (r.high % 1000) * 10 + 9;
} else if (r.low / 10000 == 0 && r.high / 10000 == 9) {
break;
} else {
r.low = (r.low % 1000) * 10;
r.high = (r.high % 1000) * 10 + 9;
output[i] = 0;
}
}
}
output[len] = '\0';
}
void decode(char* input, char* output) {
int freq[256] = {0};
int len = strlen(input);
for (int i = 0; i < len; i++) {
freq[input[i]]++;
}
int total = 0;
for (int i = 0; i < 256; i++) {
total += freq[i];
}
for (int i = 0; i < 256; i++) {
freq[i] = (freq[i] * 10000) / total;
}
Range r = {0, 9999, 10000};
int low = 0;
int high = 9999;
for (int i = 0; i < len; i++) {
int c = input[i];
int new_low = low + (r.range * freq[c]) / 10000;
int new_high = low + (r.range * freq[c+1]) / 10000 - 1;
r.low = new_low;
r.high = new_high;
int value = 0;
for (int j = 0; j < 4; j++) {
value = value * 10 + (r.low / (r.range / 10));
r.low = (r.low % (r.range / 10)) * 10;
r.high = (r.high % (r.range / 10)) * 10 + 9;
}
output[i] = value;
low += freq[value] * r.range / 10000;
high = low + freq[value+1] * r.range / 10000 - 1;
}
output[len] = '\0';
}
int main() {
char input[MAX_LEN];
char output[MAX_LEN];
printf("请输入要压缩的字符串:");
scanf("%s", input);
encode(input, output);
printf("压缩后的字符串为:");
for (int i = 0; i < strlen(input); i++) {
printf("%d", output[i]);
}
printf("\n");
decode(output, input);
printf("解压后的字符串为:%s\n", input);
return 0;
}
```
第二个问题:lua closure factory 完整代码
以下是一个简单的Lua闭包工厂函数,可以用于创建一组具有相同行为的闭包:
```lua
function make_counter()
local count = 0
return function()
count = count + 1
return count
end
end
local c1 = make_counter()
print(c1()) -- 输出 1
print(c1()) -- 输出 2
local c2 = make_counter()
print(c2()) -- 输出 1
print(c1()) -- 输出 3
```
第三个问题:中文加密
中文加密可以使用简单的替换密码,将每个中文字符替换成另一个中文字符。以下是一个简单的中文加密程序,可以将输入的中文字符串加密成另一个中文字符串:
```python
import random
def encrypt(text):
chars = list(text)
random.shuffle(chars)
return ''.join(chars)
text = input('请输入要加密的中文字符串:')
encrypted = encrypt(text)
print('加密后的字符串为:', encrypted)
```
解密时,只需要将加密后的字符串还原成原始字符串即可。
阅读全文