/* * @(#) fbitio.c - File bit I/O support functions library (source). * (c) 1998 Ivan Maidanski http://ivmai.chat.ru * Freeware function library source. All rights reserved. ** * Language: ANSI C * Tested with: Watcom C 16/32 v11.0 * Last modified: 1998-06-12 19:10:00 GMT+04:00 */ #include "fbitio.h" /* header file */ #include /* CHAR_BIT */ #include /* NULL, EOF, FILE, fgetc(), fputc(), feof() */ /* implementation section */ int fbitput(FILE *f, unsigned char *pbitbuf, int bit) { if (pbitbuf==NULL) return fputc(bit? 1 : 0,f); if (!*pbitbuf) *pbitbuf=1<<(CHAR_BIT-1); if (*pbitbuf&1) { *pbitbuf>>=1; if (bit) *pbitbuf|=1<<(CHAR_BIT-1); bit=fputc(*pbitbuf,f); *pbitbuf=0; } else { *pbitbuf>>=1; if (bit) *pbitbuf|=1<<(CHAR_BIT-1); bit=0; } return bit; } int fbitflush(FILE *f, unsigned char *pbitbuf) { int res; if (pbitbuf==NULL || !*pbitbuf) return 0; res=*pbitbuf!=(1<<(CHAR_BIT-1)); while (!(*pbitbuf&1)) *pbitbuf>>=1; if (res) res=fputc(*pbitbuf>>1,f); *pbitbuf=0; return res; } int fbitget(FILE *f, unsigned char *pbitbuf) { int bit; if (pbitbuf==NULL) return (bit=fgetc(f))==EOF? EOF : (bit? 1 : 0); bit=*pbitbuf; if (!(*pbitbuf>>=1)) { if ((bit=fgetc(f))==EOF) return EOF; *pbitbuf=(((unsigned char)bit)>>1)|(1<<(CHAR_BIT-1)); } return bit&1; } int fbiteof(FILE *f, unsigned char *pbitbuf) { return feof(f) && (pbitbuf==NULL || *pbitbuf<=1); } int fbitvalput(FILE *f, unsigned char *pbitbuf, unsigned long value, unsigned long maxval) { for (;maxval;value>>=1,maxval>>=1) if (fbitput(f,pbitbuf,value&1? 1 : 0)==EOF) return EOF; return 0; } int fbitvalget(FILE *f, unsigned char *pbitbuf, unsigned long *pvalue, unsigned long maxval) { int bit; unsigned long mask; if (pvalue==NULL) return 0; for (*pvalue=0,mask=1;mask && maxval>=mask;mask<<=1) if ((bit=fbitget(f,pbitbuf))==EOF) return EOF; else if (bit) *pvalue|=mask; bit=*pvalue>maxval; if (bit) *pvalue-=maxval+1; return bit; }