I go on reading that source of LZ77. Today I met another function. Although there are comment,
I still manage my best to understand it. Let's look at that function firstly.
void CopyBits(BYTE* memDest, int nDestPos,
BYTE* memSrc, int nSrcPos, int nBits)
{
int iByteDest = 0, iBitDest;
int iByteSrc = 0, iBitSrc = nSrcPos;
int nBitsToFill, nBitsCanFill;
while (nBits > 0)
{
// get the number of bits need filling.
nBitsToFill = min(nBits, iByteDest ? 8 : 8 - nDestPos);
// get the index of those bits need filling.
iBitDest = iByteDest ? 0 : nDestPos;
// get how many bits can fill at a time
nBitsCanFill = min(nBitsToFill, 8 - iBitSrc);
// copy bits in a byte.
CopyBitsInAByte(memDest + iByteDest, iBitDest,
memSrc + iByteSrc, iBitSrc, nBitsCanFill);
// fill remaining bits.
if (nBitsToFill > nBitsCanFill)
{
iByteSrc++; iBitSrc = 0; iBitDest += nBitsCanFill;
CopyBitsInAByte(memDest + iByteDest, iBitDest,
memSrc + iByteSrc, iBitSrc,
nBitsToFill - nBitsCanFill);
iBitSrc += nBitsToFill - nBitsCanFill;
}
else
{
iBitSrc += nBitsCanFill;
if (iBitSrc >= 8)
{
iByteSrc++; iBitSrc = 0;
}
}
nBits -= nBitsToFill;
iByteDest++;
}
}
As a matter of fact, it is not hard to understand this function. However, I made a mistake. I
ignored of the main body, and began to study statements line by line. In addition, there are two
bad variable names as parameter -- "nDestPos", "nSrcPos". They puzzled me long time. In fact,
they are used to store the index of bits. The function "CopyBitsInAByte()" mentioned yesterday
is used to copy bits in a byte. Now there are more than one byte needed copying. So, there is a
"while" loop statement. "CopyBitsInAByte(memDest + iByteDest, iBitDest, memSrc + iByteSrc,
iBitSrc, nBitsCanFill);" This statement copy some bits into a destination byte. Perhaps, there
are some remaining. "if (nBitsToFill > nBitsCanFill)" is used to check whether that case is. If
yes, copy those remaining bits into the destination byte; otherwise, work out the next source byte
and its bit index.
OK. Let's look at those statement ahead of the loop body. How to get the number of bits needed
filling. "8 - nDestPos" can get how many bits is from the specified location to the end. It means
the maximum number of bits can fill. However, real number of bits needed copying can be less than
the maximum. So, the function "min()" is used to compute the real number. If "iByteDest" is more
than 0, it means began to copying remaining bit in a new destination byte. So, the maximum is 8.
The "nBitsCanFill" represents how many bits can be copy in a dest byte. The "8 - iBitSrc" means
how many bits wait copy in a source byte. So, the value of "nBitsCanFill" must be a less number
between "8 - iBitSrc" and "nBitsToFill".