Elias gamma code is a universal code encoding positive integers. It is used most commonly when coding integers whose upper-bound cannot be determined beforehand.
Read and count 0s from the stream until you reach the first 1. Call this count of zeroes N.
Considering the one that was reached to be the first digit of the integer, with a value of 2N, read the remaining N digits of the integer.
Gamma coding is used in applications where the largest encoded value is not known ahead of time, or to compress data in which small values are much more frequent than large values.
Gamma coding does not code zero or negative integers. One way of handling zero is to add 1 before coding and then subtract 1 after decoding. Another way is to prefix each nonzero code with a 1 and then code zero as a single 0. One way to code all integers is to set up a bijection, mapping integers (0, 1, -1, 2, -2, 3, -3, ...) to (1, 2, 3, 4, 5, 6, 7, ...) before coding.
Example code
Encode
void eliasGammaEncode(char* source, char* dest){
IntReader intreader(source);
BitWriter bitwriter(dest);
while(intreader.hasLeft()){int num = intreader.getInt();
int l = log2(num);
for(int a=0; a < l; a++){
bitwriter.putBit(false); //put 0s to indicate how much bits that will follow}
bitwriter.putBit(true);//mark the end of the 0sfor(int a=0; a < l; a++)//Write the bits as plain binary{if(num & 1 << a)
bitwriter.putBit(true);
else
bitwriter.putBit(false);
}}
intreader.close();
bitwriter.close();
}
Decode
void eliasGammaDecode(char* source, char* dest){
BitReader bitreader(source);
BitWriter bitwriter(dest);
int numberBits = 0;
while(bitreader.hasLeft()){while(!bitreader.getBit() || bitreader.hasLeft())numberBits++; //keep on reading until we fetch a one...int current = 0;
for(int a=0; a < numberBits; a++)//Read numberBits bits{if(bitreader.getBit())
current += 1 << a;
}//write it as a 32 bit number
current= current | (1 << numberBits ) ; //last bit isn't encoded!for(int a=0; a < 32; a++)//Read numberBits bits{if(current & (1 << a))
bitwriter.putBit(true);
else
bitwriter.putBit(false);
}}}