Unary Coding

From WikiCoder

Unary coding is the optimal code for the probabilities 1/2, 1/4, 1/8, etc...

n (non-negative) n (strictly positive) Unary code Alternative
0 1 0 1
1 2 10 01
2 3 110 001
3 4 1110 0001
4 5 11110 00001
5 6 111110 000001
6 7 1111110 0000001
7 8 11111110 00000001
8 9 111111110 000000001
9 10 1111111110 0000000001

Code Example

void write_Unary(unsigned value) 
{
    write_bits(0, value);
    write_bits(1, 1);
}

unsigned read_Unary() 
{
    unsigned value = 0;
    do {
        ++value;
    } while(!read_bits(1));
    return value;
}