1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
/***************************************************************************
* Function : RiceEncodeFile
* Description: This routine reads an input file 1 character at a time and
* writes out a Rice encoded version of that file.
* Parameters : inFile - Name of file to encode
* outFile - Name of file to write encoded output to
* k - length of binary portion of encoded word
* Effects : File is encoded using the Rice algorithm with a k bit
* binary portion.
* Returned : TRUE for success, otherwise FALSE.
***************************************************************************/
int RiceEncodeFile(char *inFile, char *outFile, unsigned char k)
{
FILE *fpIn; /* uncoded input */
bit_file_t *bfpOut; /* encoded output */
unsigned char unary, binary; /* unary & binary portions */
unsigned char mask; /* mask for binary portion */
int c;
/* open input and output files */
if (NULL == (fpIn = fopen(inFile, "rb")))
{
perror(inFile);
return FALSE;
}
if (NULL == outFile)
{
bfpOut = MakeBitFile(stdout, BF_WRITE);
}
else
{
if (NULL == (bfpOut = BitFileOpen(outFile, BF_WRITE)))
{
fclose(fpIn);
perror(outFile);
return FALSE;
}
}
mask = 0xFF >> (CHAR_BIT - k);// 0xFF * 3 =
/* encode input file one byte at a time */
while ((c = fgetc(fpIn)) != EOF)
{
/* compute the unary portion */
unary = (unsigned char)c;
unary >>= k;
while (unary > 0)
{
/* write out unary worth of 1s */
unary--;
BitFilePutBit(1, bfpOut);
}
/* write an ending 0 */
BitFilePutBit(0, bfpOut);
/* binary portion */
binary = (unsigned char)c & mask;
binary <<= (CHAR_BIT - k); /* right justify bits */
BitFilePutBits(bfpOut, &binary, k);
}
/* pad fill with 1s so decode will run into EOF */
BitFileFlushOutput(bfpOut, TRUE);
fclose(fpIn);
BitFileClose(bfpOut);
return TRUE;
}
|