Unary Code
Unary encoding writes the positive integer i as i−1 zeroes followed by a 1, c(i) = 0^(i−1)1; it is prefix-free and entropy-optimal for Pr(X = x) = 2^(−x).
Know these firstPrefix-Free Code
Formula#
Code length bits.
| 1 | 1 |
| 2 | 01 |
| 3 | 001 |
| 4 | 0001 |
| 5 | 00001 |
Properties#
- Prefix-free. Each codeword ends at its first
1; all bits before it are0. A shorter codeword would have its1at an earlier position, so it cannot be a prefix of a longer one (DBIS Exam WS1516 (not published), Task 2.1). - Decoding: count zeroes up to the next
1; invalid only if the bit string ends in zeroes (then return the empty array in the exam’s decode function). - Entropy-optimal for (geometric distribution with ): , and (Entropy-Optimal Code). This is exactly the distribution of the random process “flip a fair coin until the first 1”: .
- Not optimal for other distributions, e.g. uniform on : the expected code length of a sequence of such integers is bits, while the entropy-optimal fixed-length code needs about bits per number (DBIS Exam WS1718 (not published), Task 2.2–2.4).
- Used as the quotient part of Golomb codes.
Example#
Decode 110000100111001 (DBIS Exam WS1516 (not published), Task 2.1): 1|1|00001|001|1|1|001 .
def unary_encode(numbers):
bits = []
for i in numbers:
bits.extend([0] * (i - 1) + [1])
return bits
Sources#
- DBIS Exam WS1516 (not published) Task 2, DBIS Exam WS1718 (not published) Task 2
- Not lectured in WS 25/26.