 elias gamma code is a universal code encoding positive integers developed by peter elias. it is used most commonly when coding integers whose upper-bound cannot be determined beforehand. ==encoding== to code a number: #write it in binary. #subtract 1 from the number of bits written in step 1 and prepend that many zeros. an equivalent way to express the same process: #separate the integer into the highest power of 2 it contains (2n) and the remaining n binary digits of the integer. #encode n in unary; that is, as n zeroes followed by a one. #append the remaining n binary digits to this representation of n. to represent a number x, elias gamma uses 2 \lfloor \log_2(x) \rfloor + 1 bits. the code begins (the implied probability distribution for the code is added for clarity): {| class=wikitable ! number !! encoding !! 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 |- | 10 = 23 + 2 || 0001010 || 1/128 |- | 11 = 23 + 3 || 0001011 || 1/128 |- | 12 = 23 + 4 || 0001100 || 1/128 |- | 13 = 23 + 5 || 0001101 || 1/128 |- | 14 = 23 + 6 || 0001110 || 1/128 |- | 15 = 23 + 7 || 0001111 || 1/128 |- | 16 = 24 + 0 || 000010000 || 1/512 |- | 17 = 24 + 1 || 000010001 || 1/512 |} ==decoding== to decode an elias gamma-coded integer: #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. ==uses== 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. == generalizations == 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, 
Lossless_compression_algorithms Numeral_systems