Python中的 Elias Delta 解码
在本文中,我们将使用Python实现 Elias Delta Decoding。
Peter Elias 设计了 Elias delta 代码,这是一个用于编码正整数的通用系统。
句法:
Elias Delta Encoding(X)= Elias Gamma encoding (1+floor(log2(X))) + Binary representation of X without MSB.
方法:
- 导入所需的库并从用户那里读取编码的二进制字符串。
- 从最高有效位读取/计数零的数量,直到看到第一个“1”并将其存储在名为“L”的变量中
句法:
L=0
while True:
if not x[L] == '0':
break
L= L + 1
- 将“L”视为第一个数字并读取 L 更多位并删除所有位,直到当前 L 位。
- 取出剩余位并在最高有效位中添加“1”。
句法:
x.insert(0,’1′)
- 将最终的二进制转换为整数,得到原始数字。
例子:
Let the input encoded string is 01111
Step1: Read/Count the number of zeros from most significant bit until you see the first ‘1’ and store it in ‘L’ until you see the first ‘1’
In our case, L=1
Step2: Consider that ‘1’ as first digit read L more bits (1 more bit) and drop everything.
01111= 11
Step3: Takeout the remaining bits and prepend with ‘1’ in MSB.
111
Step4: Convert the final binary string into integer which gives us 7.
下面是实现。
示例 1:生成与某个值对应的 Elias Delta 解码值的示例。
Python3
import math
def Elias_Delta_Decoding(x):
x = list(x)
L = 0
while True:
if not x[L] == '0':
break
L = L + 1
# Reading L more bits and dropping ALL
x = x[2*L+1:]
# Prepending with 1 in MSB
x.reverse()
x.insert(0, '1')
n = 0
# Converting binary to integer
for i in range(len(x)):
if x[i] == '1':
n = n+math.pow(2, i)
return int(n)
x = '01111'
print(Elias_Delta_Decoding(x))
Python
import math
def Elias_Delta_Decoding(x):
x = list(x)
L=0
while True:
if not x[L] == '0':
break
L= L + 1
# Reading L more bits and dropping ALL
x=x[2*L+1:]
# Prepending with 1 in MSB
x.insert(0,'1')
x.reverse()
n=0
# Converting binary to integer
for i in range(len(x)):
if x[i]=='1':
n=n+math.pow(2,i)
return int(n)
x = '0111100'
print(Elias_Delta_Decoding(x))
输出:
7
示例 2:生成对应于某个 value.p 的 Elias Delta Decoding 值的示例
Python
import math
def Elias_Delta_Decoding(x):
x = list(x)
L=0
while True:
if not x[L] == '0':
break
L= L + 1
# Reading L more bits and dropping ALL
x=x[2*L+1:]
# Prepending with 1 in MSB
x.insert(0,'1')
x.reverse()
n=0
# Converting binary to integer
for i in range(len(x)):
if x[i]=='1':
n=n+math.pow(2,i)
return int(n)
x = '0111100'
print(Elias_Delta_Decoding(x))
输出:
28