home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / FREEZE-2.ZIP / bitio.c next >
C/C++ Source or Header  |  1992-07-18  |  2KB  |  82 lines

  1. #include "freeze.h"
  2. #include "bitio.h"
  3.  
  4. ul_t     getbuf = 0;     /* assume sizeof (ul_t) >= 4 */
  5. us_t     putbuf;
  6. uc_t     bitlen = 0, __, crpt_flag = 0;
  7.  
  8. /* get N bits (N <= 16), returning in Bit(N-1)...Bit 0 */
  9.  
  10. short GetNBits (n)
  11.     register us_t n;
  12. {
  13.     register ul_t dx = getbuf;
  14.     register uc_t c;
  15.  
  16.     static us_t mask[17] = {
  17.         0x0000,
  18.         0x0001, 0x0003, 0x0007, 0x000f,
  19.         0x001f, 0x003f, 0x007f, 0x00ff,
  20.         0x01ff, 0x03ff, 0x07ff, 0x0fff,
  21.         0x1fff, 0x3fff, 0x7fff, 0xffff };
  22.  
  23.     while (bitlen < n)
  24.         {
  25.             c = getchar ();
  26.             dx |= (ul_t) c << (BYSH - bitlen);
  27.             bitlen += 8;
  28.         }
  29.     crpt_flag = feof(stdin);
  30.     getbuf = dx << n;
  31.     bitlen -= n;
  32.     return (dx >> (bits(getbuf) - n)) & mask[n];
  33. }
  34.  
  35. /* output `l' high bits of `c' */
  36.  
  37. void Putcode (l, c)
  38.     register us_t l;
  39.     us_t c;
  40. {
  41.     register us_t len = bitlen;
  42.     register us_t b = (us_t)putbuf;
  43.     b |= c >> len;
  44.     if ((len += l) >= 8) {
  45.         putchar ((int)(b >> 8));
  46.         if ((len -= 8) >= 8) {
  47.             putchar ((int)b);
  48.             bytes_out += 2;
  49.             len -= 8;
  50.             b = c << (l - len);
  51.         } else {
  52.             b <<= 8;
  53.             bytes_out++;
  54.         }
  55.     }
  56.     if (ferror(stdout))
  57.         writeerr();
  58.     putbuf = b;
  59.     bitlen = len;
  60. }
  61.  
  62.  
  63. /* Flushes the bit I/O buffers and check the state of stdout */
  64.  
  65. void EncodeEnd ()
  66. {
  67.     if (bitlen) {
  68.         putchar((int)(putbuf >> 8));
  69.         bytes_out++;
  70.         if (ferror(stdout))
  71.             writeerr();
  72.     }
  73. }
  74.  
  75. /* File too short or invalid header, print a message */
  76.  
  77. void crpt_message ( )
  78. {
  79.     fprintf ( stderr, "melt: corrupt input\n" );
  80. }
  81.  
  82.