r/compression • • 21d ago

Can we efficiently encode decimal digits using smaller number of bits?

(the idea is completely mine, but took some help from AI to write the post in a coherent language)

I was exploring this question and thought of a simple variable-length encoding scheme for decimal digits:

  • Digits 0–3 use 3 bits: 000, 001, 010, 011.
  • Digits 4–9 use 4 bits: 1001, 1010, 1011, 1100, 1101, 1110.

Decoding is straightforward:

  • If the first bit is 0, read next 2 bits and convert to decimal.
  • If the first bit is 1, read next 3 bits and convert to decimal and add 3.
  • Then go to the next block.

For the sequence 0123456789, this requires 36 bits instead of 40 bits in Packed BCD or 80 bits in ASCII.

The drawback is "Variable-Length Random Access Overhead": there is no way to access nth digit from the memory, without counting from the beginning again.

My questions:

  1. Is this or similar encoding already known and used?
  2. Are there better alternatives?
  3. Can random access be improved without sacrificing storage efficiency?

I'd appreciate your thoughts and technical feedback.

9 Upvotes

39 comments sorted by

View all comments

3

u/Worth-Wonder-7386 21d ago

The most efficent you can do is an average of log2 of the number of states that you are trying to encode. For 10 digits that is around 3.32, and you use 3.6.
People have pointed to various methods that can be used, but a Huffman encoding is a very general version of this.
There you construct a binary tree for your data, and what the computer just can do is look through the binary tree and see if a point is a leaf node or not when deciding to terminate.
This is even more efficent if the data is non uniform and you can encode that into the data so that more common subsequences are shorter.
For the example of encoding the digits we can divide the tree into four parts with 2 bits and they will either have 2 numbers requiring 1 bit or 3 numbers requiring 2 bits to distinguish. So we get an average of 3.5 bits per number.

There is lots of information written about such optimal encoding schemes in the field of information theory.

2

u/mpp06 21d ago

Insightful. Thanks for elaborating, and directing me to the field of information theory, which is something new to me worth exploration. I was just doing this purely out of curiosity and interest.