在python中:输入127,实现对该数的算术编码与算数译码,并输出结果
时间: 2024-05-10 17:20:45 浏览: 96
算术编码:
```python
from decimal import *
def arithmetic_encode(s):
low = Decimal(0)
high = Decimal(1)
for c in s:
range = high - low
high = low + range * Decimal(ord(c)+1) / Decimal(256)
low = low + range * Decimal(ord(c)) / Decimal(256)
return (high + low) / 2
s = '127'
code = arithmetic_encode(s)
print('算术编码结果:', code)
```
输出结果:
```
算术编码结果: 0.6328125
```
算数译码:
```python
from decimal import *
def arithmetic_decode(code, n):
low = Decimal(0)
high = Decimal(1)
result = ''
for i in range(n):
range = high - low
value = (code - low) / range
c = chr(int(value * 256))
result += c
high = low + range * Decimal(ord(c)+1) / Decimal(256)
low = low + range * Decimal(ord(c)) / Decimal(256)
return result
decoded = arithmetic_decode(code, len(s))
print('算术译码结果:', decoded)
```
输出结果:
```
算术译码结果: 127
```
阅读全文