I'm trying to map the table 3.2.5 from RFC1951 from its distance values to code values. The table as follows (ignore the bits column, ranges are inclusive):
Code Bits Dist Code Bits Dist Code Bits Distance
---- ---- ---- ---- ---- ------ ---- ---- --------
0 0 1 10 4 33-48 20 9 1025-1536
1 0 2 11 4 49-64 21 9 1537-2048
2 0 3 12 5 65-96 22 10 2049-3072
3 0 4 13 5 97-128 23 10 3073-4096
4 1 5,6 14 6 129-192 24 11 4097-6144
5 1 7,8 15 6 193-256 25 11 6145-8192
6 2 9-12 16 7 257-384 26 12 8193-12288
7 2 13-16 17 7 385-512 27 12 12289-16384
8 3 17-24 18 8 513-768 28 13 16385-24576
9 3 25-32 19 8 769-1024 29 13 24577-32768
I need a mathematical function that maps the distance values to the code values e.g. f(777) = 19, f(9000) = 26. Both input and output values are integer and I know there must be some expression that would work using Log2 functions. The range of distance doubles every 2 codes (except code 0 and 1) e.g. there are 4096 distinct values for codes 26 and 27, 8192 for 28 and 29, etc.
Exceptions can be made for codes 0 and 1
In the end, I figured the simplest solution is to just map all the values rather than calculating it each time. In python:
and then just reference the value by
code = DISTANCE_CODES[distance]. Note that distance cannot be 0 and the value atDISTANCE_CODES[0]is invalid but necessary as python index starts from 0.