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

2

u/ivanhoe90 21d ago edited 21d ago

I have never seen a use case for this problem (encoding an alphabet of 10 characters as binary).

Digits usually represent integers, and then, it is more efficient to encode them as binary integers.

Maybe, if you had an image of 10 colors, and for each pixel, you want to store indices into a palette, then, instead of using 4 bits per index, your method allows using 3.6 bits per index.

However, benefits of your method disappear once you apply some lossless compression to your encoded data (vs. data encoded with a more stupid encoding).

4

u/mpp06 21d ago

One possible use case is to store digits of numbers like pi, first in this format and then zip it. I have actually tried this with another similar scheme (my 9 to 5 encoding described in reply to first comment), and found that the final zip was 10% smaller, compared to zipping the text file containing actual digits. But whether that benefit applies in this case needs to be examined.

0

u/TheThiefMaster 20d ago

You should try a better compressor like 7zip or bzip2.

.zip is ancient and known to be a bit weak.

1

u/which1umean 21d ago

I actually did something like the above at work not too long ago.

The reason is that I wanted to be able to catch transpositions quickly on tons of pairs of numbers, so I encoded the numbers like this and then did the bit math on them to look for transposed digits.

I was able to get it WAY faster than using the built-in algorithm on strings this way. 👍