Elias gamma coding

[1]: 199 The code begins (the implied probability distribution for the code is added for clarity): To decode an Elias gamma-coded integer: Gamma coding is used in applications where the largest encoded value is not known ahead of time, or to compress data[dubious – discuss] in which small values are much more frequent than large values.

Gamma coding can be more size efficient in those situations.

For example, note that, in the table above, if a fixed 8-bit size is chosen to store a small number like the number 5, the resulting binary would be 00000101, while the γ-encoding variable-bit version would be 00 1 01, needing 3 bits less.

On the contrary, bigger values, like 254 stored in fixed 8-bit size, would be 11111110 while the γ-encoding variable-bit version would be 0000000 1 1111110, needing 7 extra bits.

One way of handling zero is to add 1 before coding and then subtract 1 after decoding.

In software, this is most easily done by mapping non-negative inputs to odd outputs, and negative inputs to even outputs, so the least-significant bit becomes an inverted sign bit:

It involves dividing the number by a positive divisor, commonly a power of 2, writing the gamma code for one more than the quotient, and writing out the remainder in an ordinary binary code.