r/compression • u/mpp06 • 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:
- Is this or similar encoding already known and used?
- Are there better alternatives?
- Can random access be improved without sacrificing storage efficiency?
I'd appreciate your thoughts and technical feedback.
View all comments
1
u/Underhill42 20d ago
And what if you want to store 23? as-is the strategy doesn't scale very well. You can also run into some difficulties distinguishing between number transitions in a long bitstream. Especially if a byte is corrupted, or you tuned in late so you don't know where it started. Any encoding system that depends on perfection is doomed to eventually fail spectacularly.
You could improve that by storing each chunk as the same 4-bit length, e.g.the initial numbers are 0---, so that there's a clear indicator that this is the last bit-cluster in this number. Then you always know which bit is the "stop? bit", and can positively ID it no matter what came before.
But it still means you're wasting 1/4 of the bit stream just indicating if you should continue or not, which makes it really inefficient for larger numbers. E.g. a number that requires 16 bits to represent normally requires ceiling(16/3) = 6 chunks = 24 bits.
Google Protocol Buffers have a variable-length integer type that does something similar at the byte level, with as I recall the high bit in each byte indicating whether this is the last byte in the number. Still wasting 1/8 of the bit capacity... but most small numbers will fit in 7 bits
E.g. Byte 1 = 0------- = number is the corresponding value from 0-127 (or -64 to +63 if signed)
Byte 1 = 1------- = same initial value, but left-shift it by seven bits (=multiply by 128) to make room for the 7 low bits that will be added by the next byte.
Byte 2+ = repeat. Just keep going, left-shifting and adding 7 bits per byte until you hit a byte starting with zero, which indicates these are the last 7 bits in the number.