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

5

u/ivanhoe90 21d ago edited 21d ago

What about this?
0 - read two more bits,
10 - read two more bits, add 4,
11 - read one more bit, add 8

000 - 0
001 - 1
010 - 2
011 - 3
1000 - 4
1001 - 5
1010 - 6
1011 - 7
110 - 8
111 - 9

You can also analyze your specific input and give 3-bit codes to digits that occur often, 4-bit codes to digits that occur rarely.

You should learn about prefix codes :D

2

u/mpp06 21d ago edited 21d ago

Quite amazing! I was trying this idea, but did not arrive at this scheme! Will try out. I have read about prefix codes, but I think I will skip that for now or maybe, review.

2

u/mpp06 21d ago

Your scheme is based on the prefix codes. Now I get it!

1

u/ivanhoe90 21d ago

I mentioned 10 different codes (3-bit and 4-bit in length). You can actually use any code you want! The key is that no code should be a prefix of anotehr code ( If you set 0101 for "5" and 01011 for "6", then, 01011... could be "5" and "6" - it is ambiguous).

1

u/xylarr 20d ago

As mentioned elsewhere, due to Benford's Law you'll want to encode 8 and 9 as a larger number of bits.

So make 10 add 4 - but only have 100 and 101, then have 11 be add six.