1 /* ------------------------------------------------------------------------ */
2 /* LHa for UNIX */
3 /* bitio.c -- bit stream */
4 /* */
5 /* Modified Nobutaka Watazaki */
6 /* */
7 /* Ver. 1.14 Source All chagned 1995.01.14 N.Watazaki */
8 /* Separated from crcio.c 2002.10.26 Koji Arai */
9 /* ------------------------------------------------------------------------ */
10 #include "lha.h"
11
12 static unsigned char subbitbuf, bitcount;
13
14 void
fillbuf(n)15 fillbuf(n) /* Shift bitbuf n bits left, read n bits */
16 unsigned char n;
17 {
18 while (n > bitcount) {
19 n -= bitcount;
20 bitbuf = (bitbuf << bitcount) + (subbitbuf >> (CHAR_BIT - bitcount));
21 if (compsize != 0) {
22 compsize--;
23 subbitbuf = (unsigned char) getc(infile);
24 }
25 else
26 subbitbuf = 0;
27 bitcount = CHAR_BIT;
28 }
29 bitcount -= n;
30 bitbuf = (bitbuf << n) + (subbitbuf >> (CHAR_BIT - n));
31 subbitbuf <<= n;
32 }
33
34 unsigned short
getbits(n)35 getbits(n)
36 unsigned char n;
37 {
38 unsigned short x;
39
40 x = bitbuf >> (2 * CHAR_BIT - n);
41 fillbuf(n);
42 return x;
43 }
44
45 void
putcode(n,x)46 putcode(n, x) /* Write leftmost n bits of x */
47 unsigned char n;
48 unsigned short x;
49 {
50 while (n >= bitcount) {
51 n -= bitcount;
52 subbitbuf += x >> (USHRT_BIT - bitcount);
53 x <<= bitcount;
54 if (compsize < origsize) {
55 if (fwrite(&subbitbuf, 1, 1, outfile) == 0) {
56 fatal_error("Write error in bitio.c(putcode)");
57 }
58 compsize++;
59 }
60 else
61 unpackable = 1;
62 subbitbuf = 0;
63 bitcount = CHAR_BIT;
64 }
65 subbitbuf += x >> (USHRT_BIT - bitcount);
66 bitcount -= n;
67 }
68
69 void
putbits(n,x)70 putbits(n, x) /* Write rightmost n bits of x */
71 unsigned char n;
72 unsigned short x;
73 {
74 x <<= USHRT_BIT - n;
75 putcode(n, x);
76 }
77
78 void
init_getbits()79 init_getbits( /* void */ )
80 {
81 bitbuf = 0;
82 subbitbuf = 0;
83 bitcount = 0;
84 fillbuf(2 * CHAR_BIT);
85 }
86
87 void
init_putbits()88 init_putbits( /* void */ )
89 {
90 bitcount = CHAR_BIT;
91 subbitbuf = 0;
92 }
93