Elias Gamma Coding
即Gamma编码,是一种对正整数进行编码的统一编码,由Peter Elias发明。适用于预先无法获知最大编码整数的情况,而且小整数出现频率高,大整数出现频率低的情况。
编码原理:
对任何正整数NUM,对INT(Log2(NUM))+1进行一元编码,后缀上NUM二进制串除去最高位的子串。如5的编码为001,01。
编码示例:
NUM | EliasGamma Code | Implied probability |
1 = 20 + 0 | 1 | 1/2 |
2 = 21 + 0 | 010 | 1/8 |
3 = 21 + 1 | 011 | 1/8 |
4 = 22 + 0 | 00100 | 1/32 |
5 = 22 + 1 | 00101 | 1/32 |
6 = 22 + 2 | 00110 | 1/32 |
7 = 22 + 3 | 00111 | 1/32 |
8 = 23 + 0 | 0001000 | 1/128 |
9 = 23 + 1 | 0001001 | 1/128 |
编码、解码算法:
/****************************************************
Encode_EliasGamma:
Encoding algorithm of EliasGamma Coding.
*****************************************************/
int Encode_EliasGamma(int *pSourceData,char *pEncodedData,int nSourceDataLen,int &nEncodedDataLen)
{
//Encoding EliasGamma Coding.
int k=-1;
for(int i=0;i<nSourceDataLen;i++)
{
int num = pSourceData[i];
int numPow = int(log10(num + 0.0)/log10(2+ 0.0));
int j = 0;
for ( j=0; j < numPow; j++) pEncodedData[++k]=0;
pEncodedData[++k]=1;
for (j=numPow-1; j >= 0; j--)
{
if (num & 1 << j) pEncodedData[++k]=1;
else pEncodedData[++k]=0;
}
nEncodedDataLen=k+1;
}
//End of Encoding.
return 1;
}
/****************************************************
Decode_EliasGamma:
Decoding algorithm of EliasGamma Coding.
*****************************************************/
int Decode_EliasGamma(int *pDecodedData,char *pEncodedData,int &nDecodedDataLen,int nEncodedDataLen)
{
int i=0,j=0;
while (1)
{
int numPow = 0;
while (!pEncodedData[i++]) numPow++;
if(numPow >=48) break;
int num = 0;
for (int h=numPow-1; h >= 0; h--)
if (pEncodedData[i++]) num |= 1 << h;
num |= 1 << numPow;
pDecodedData[j++]=num;
}
nDecodedDataLen=j;
return 1;
}