1 /***********************************************************
3 ***********************************************************/
7 #define CRCPOLY 0xA001 /* ANSI CRC-16 */
10 ushort crctable[UCHAR_MAX + 1];
17 for (i = 0; i <= UCHAR_MAX; i++) {
19 for (j = 0; j < CHAR_BIT; j++)
21 r = (r >> 1) ^ CRCPOLY;
30 shift bitbuf n bits left, read n bits
34 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
35 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
37 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50 bitcount (size of subbitbuf data)
55 bitstring(unsigned int bitbuf, int n, char *ptr, size_t sz)
66 return "bit size is too big";
71 str[--n] = (bitbuf & 1) ? '1' : '0';
78 fillbuf(struct lzh_istream *rp, int n)
80 assert(n <= BITBUFSIZ);
98 while (n > rp->bitcount) {
99 /* set left (n - bitcount) bits from subbitbuf */
100 /* subbitbuf is extended unsigned int */
102 rp->bitbuf |= rp->subbitbuf << n;
103 if (rp->compsize != 0) {
105 rp->subbitbuf = (uchar) getc(rp->fp);
109 rp->bitcount = CHAR_BIT;
111 /* set n bits from subbitbuf */
113 rp->bitbuf |= (rp->subbitbuf >> rp->bitcount) & ((1 << n)-1);
117 getbits(struct lzh_istream *rp, int n)
121 x = rp->bitbuf >> (BITBUFSIZ - n);
127 putbits(struct lzh_ostream *wp, int n, uint x)
128 { /* Write rightmost n bits of x */
129 if (n < wp->bitcount) {
130 wp->subbitbuf |= x << (wp->bitcount -= n);
133 if (wp->compsize < wp->origsize) {
134 putc(wp->subbitbuf | (x >> (n -= wp->bitcount)), wp->fp);
140 wp->subbitbuf = x << (wp->bitcount = CHAR_BIT - n);
143 if (wp->compsize < wp->origsize) {
144 putc(x >> (n - CHAR_BIT), wp->fp);
149 wp->subbitbuf = x << (wp->bitcount = 2 * CHAR_BIT - n);
155 fread_crc(void *p, int n, FILE * f, unsigned int *crc)
159 i = n = fread(p, 1, n, f);
162 UPDATE_CRC(*crc, *(unsigned char*)p++);
168 fwrite_crc(void *p, int n, FILE * f, unsigned int *crc)
170 if (fwrite(p, 1, n, f) < n)
171 error("Unable to write");
174 UPDATE_CRC(*crc, *(unsigned char*)p++);
179 init_getbits(struct lzh_istream *rp)
184 fillbuf(rp, BITBUFSIZ);
188 init_putbits(struct lzh_ostream *wp)
190 wp->bitcount = CHAR_BIT;