April 2nd Monday (四月 二日 月曜日)

来源:互联网 发布:干部网络培训工作总结 编辑:程序博客网 时间:2024/04/29 03:03

  Today I began to read the source of LZ77.  However, I almost met a difficult at once.  There is
a function which is used to copy some bits from a byte to another byte.

  I had a look at this function.  There are two steps to set bits.  Firstly, it set all bits "1"
needed.  Secondly, it set all bits "0" needed.

void CopyBitsInAByte(BYTE* memDest, int nDestPos,
  BYTE* memSrc, int nSrcPos, int nBits)
{
 BYTE b1, b2;
 b1 = *memSrc;
 b1 <<= nSrcPos; b1 >>= 8 - nBits; // clearn bits except for needs
 b1 <<= 8 - nBits - nDestPos;  // adjust the correct position
 *memDest |= b1;  // set all 1 bits.

 b2 = 0xff; b2 <<= 8 - nDestPos;  // fill 1 into bits except for needs
 b1 |= b2;
 b2 = 0xff; b2 >>= nDestPos + nBits;
 b1 |= b2;
 *memDest &= b1;  // set all 0 bits.
}

  The above function is not complicated.  But it is not easy to understand.  Firstly, it clearn
all bits except for bits segment need copying.  From "or" operating, those bits 0 was set.  Other
bits keep its original content.  This time, the "b1" is alike "0...0XXX0..0".  At second step, the
"b1" must be set style like "1..1XXX1..1".  This time, by "and" operating all bits 1 set and other
bits are not modified.