コード例 #1
0
/*
** Read command line params, call search
*/
int
main(int argc, char *argv[]) {

    if (argc != 4) {
        usage(argv[0]);
        return(-1);
    }

    // plotter is not really a "grid" but why not use the read routine
    // to save coding!
    grid_t *sonar   = readGrid(strcmp(argv[1],"-")?fopen(argv[1],"r"):stdin, TRUE);
    grid_t *actual  = readGrid(strcmp(argv[2],"-")?fopen(argv[2],"r"):stdin, TRUE);
    grid_t *plotter = readGrid(strcmp(argv[3],"-")?fopen(argv[3],"r"):stdin, FALSE);

    assert(sonar);
    assert(actual);
    assert(plotter);

    // create output file
    char i = argv[2][6];
    char output_file_name[] = "actual1.txt.bit";
    output_file_name[6] = i;

    bit_file_t *bitfile = BitFileOpen(output_file_name, BF_WRITE);
    assert(bitfile);

    uint32_t bits_sent=0, moves_made=0;
    data_t current_position = plotter->data[0];
    for(int i = 0 ; i < plotter->width * plotter->height ; i++) {
        data_t new_position = plotter->data[i];
        moves_made += gridDistance(plotter, current_position, new_position);
        current_position = new_position;

        //store the PBF of difference between sonar reading and actual height in tempArray
        char tempArray[PBFLIMIT];
        int inaccuracy = sonar->data[current_position] - actual->data[current_position];
        int numBits, i;
        numBits = intToPBF(inaccuracy, tempArray, PBFLIMIT);

        //put the PBF into output file
        for (i = 0; i < numBits; i++) {
            BitFilePutBit((int)tempArray[i] - ASCII_ZERO, bitfile);
        }

        bits_sent += numBits;
    }

    assert(!BitFileClose(bitfile));

    printf("M: %10d B: %10d Bat: %10.1f\n",
           moves_made, bits_sent,
           (float)moves_made/(float)MOVES_PER_BATTERY + (float)bits_sent);

    return 0;
}
コード例 #2
0
/****************************************************************************
*   Function   : EncodeLZSSByFile
*   Description: This function will read an input file and write an output
*                file encoded according to the traditional LZSS algorithm.
*                This algorithm encodes strings as 16 bits (a 12 bit offset
*                + a 4 bit length).
*   Parameters : fpIn - pointer to the open binary file to encode
*                fpOut - pointer to the open binary file to write encoded
*                       output
*   Effects    : fpIn is encoded and written to fpOut.  Neither file is
*                closed after exit.
*   Returned   : EXIT_SUCCESS or EXIT_FAILURE
****************************************************************************/
int EncodeLZSSByFile(FILE *fpIn, FILE *fpOut)
{
    bit_file_t *bfpOut;

    encoded_string_t matchData;
    unsigned int i, c;
    unsigned int len;                       /* length of string */

    /* head of sliding window and lookahead */
    unsigned int windowHead, uncodedHead;

    /* use stdin if no input file */
    if (fpIn == NULL)
    {
        fpIn = stdin;
    }

    if (fpOut == NULL)
    {
        /* use stdout if no output file */
        bfpOut = MakeBitFile(stdout, BF_WRITE);
    }
    else
    {
        /* convert output file to bitfile */
        bfpOut = MakeBitFile(fpOut, BF_WRITE);
    }

    windowHead = 0;
    uncodedHead = 0;

    /* Window Size : 2^12 same as offset  */
    /************************************************************************
    * Fill the sliding window buffer with some known vales.  DecodeLZSS must
    * use the same values.  If common characters are used, there's an
    * increased chance of matching to the earlier strings.
    ************************************************************************/
    memset(slidingWindow, ' ', WINDOW_SIZE * sizeof(unsigned char));

    /* MAX_CODED : 2 to 17 because we cant have 0 to 1 */
    /************************************************************************
    * Copy MAX_CODED bytes from the input file into the uncoded lookahead
    * buffer.
    ************************************************************************/
    for (len = 0; len < MAX_CODED && (c = getc(fpIn)) != EOF; len++)
    {
        uncodedLookahead[len] = c;
    }

    if (len == 0)
    {
        return (EXIT_SUCCESS);   /* inFile was empty */
    }

    /* Look for matching string in sliding window */
    InitializeSearchStructures();
    matchData = FindMatch(windowHead, uncodedHead);

    /* now encoded the rest of the file until an EOF is read */
    while (len > 0)
    {
        if (matchData.length > len)
        {
            /* garbage beyond last data happened to extend match length */
            matchData.length = len;
        }

        if (matchData.length <= MAX_UNCODED)
        {
            /* not long enough match.  write uncoded flag and character */
            BitFilePutBit(UNCODED, bfpOut);
            BitFilePutChar(uncodedLookahead[uncodedHead], bfpOut);

            matchData.length = 1;   /* set to 1 for 1 byte uncoded */
        }
        else
        {
            unsigned int adjustedLen;

            /* adjust the length of the match so minimun encoded len is 0*/
            adjustedLen = matchData.length - (MAX_UNCODED + 1);

            /* match length > MAX_UNCODED.  Encode as offset and length. */
            BitFilePutBit(ENCODED, bfpOut);
            BitFilePutBitsInt(bfpOut, &matchData.offset, OFFSET_BITS,
                sizeof(unsigned int));
            BitFilePutBitsInt(bfpOut, &adjustedLen, LENGTH_BITS,
                sizeof(unsigned int));
        }

        /********************************************************************
        * Replace the matchData.length worth of bytes we've matched in the
        * sliding window with new bytes from the input file.
        ********************************************************************/
        i = 0;
        while ((i < matchData.length) && ((c = getc(fpIn)) != EOF))
        {
            /* add old byte into sliding window and new into lookahead */
            ReplaceChar(windowHead, uncodedLookahead[uncodedHead]);
            uncodedLookahead[uncodedHead] = c;
            windowHead = Wrap((windowHead + 1), WINDOW_SIZE);
            uncodedHead = Wrap((uncodedHead + 1), MAX_CODED);
            i++;
        }

        /* handle case where we hit EOF before filling lookahead */
        while (i < matchData.length)
        {
            ReplaceChar(windowHead, uncodedLookahead[uncodedHead]);
            /* nothing to add to lookahead here */
            windowHead = Wrap((windowHead + 1), WINDOW_SIZE);
            uncodedHead = Wrap((uncodedHead + 1), MAX_CODED);
            len--;
            i++;
        }

        /* find match for the remaining characters */
        matchData = FindMatch(windowHead, uncodedHead);
    }

    /* we've decoded everything, free bitfile structure */
    BitFileToFILE(bfpOut);

   return (EXIT_SUCCESS);
}
コード例 #3
0
ファイル: DWT.cpp プロジェクト: duythanhphan/DWTCodec
/**
  * Saves a DWT file
  */
void DWT::save(const string &fileName)
{
	FILE *fHan = fopen(fileName.data(), "wb");

	// Header
	fwrite(&magic, 1, 2, fHan);
#ifdef __BIG_ENDIAN__
	// Correct endianness for writing
	bpp = swap_endian32(bpp);
	realWidth = swap_endian32(realWidth);
	realHeight = swap_endian32(realHeight);
#endif
	fwrite(&bpp, sizeof(bpp), 1, fHan);
	fwrite(&realWidth, sizeof(int), 1, fHan);
	fwrite(&realHeight, sizeof(int), 1, fHan);
#ifdef __BIG_ENDIAN__
	// Revert endianness
	bpp = swap_endian32(bpp);
	realWidth = swap_endian32(realWidth);
	realHeight = swap_endian32(realHeight);
#endif

	// Drops half of the padding when writing
	unsigned int stopHeight = height - (height - realHeight)/2;
	unsigned int stopWidth = width - (width - realWidth)/2;
	unsigned int stopPrHeight = stopHeight * PREVIEW / height;
	unsigned int stopPrWidth = stopWidth * PREVIEW / width;

	// Looking for the highest absolute value in the transformation, used for quantization
	float maxAbsValF = 0;
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++){
			if (i >= PREVIEW || j >= PREVIEW) {
				if (abs(coeff[i*width+j]) > maxAbsValF) maxAbsValF = abs(coeff[i*width+j]);
			}
		}
	}
	int maxAbsVal = round(maxAbsValF);
	cout << "maxValue: " << maxAbsVal << endl;
	fwrite(&maxAbsVal, sizeof(int), 1, fHan);

	const float C = ((1 << (bpp-1))-1)/(float)(maxAbsVal);	// Range value
	const float M = (1 << (bpp-1));							// Added to get only positive values
	float W = 1, w = 1/sqrt(2);							// Factor of multiplication for preview
	for (unsigned int i = PREVIEW; i < height; i <<= 1) W *= w;
	for (unsigned int i = PREVIEW; i < width; i <<= 1) W *= w;

	// Huffman, searching for occurrences in the quantization
	unsigned int *occ = new unsigned int[1 << bpp];
	memset(occ, 0, (1 << bpp)*sizeof(int));
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++){
			if (i >= PREVIEW || j >= PREVIEW) {
				float quant = coeff[i * width + j] * C;
				if (abs(quant) >= .5f)
					occ[range(round(quant + M))]++;
			}
		}
	}
	Huffman *huffman = new Huffman(bpp);
	huffman->buildTree(occ, 1<<bpp);
	delete[] occ;

	// Encoding of the preview
	for (unsigned int i = 0; i < stopPrHeight && i < PREVIEW; i++) {
		for (unsigned int j = 0; j < stopPrWidth && j < PREVIEW; j++) {
			unsigned char l = coeff[i*width + j] * W;
			fwrite(&l, 1, 1, fHan);
		}
	}

	// Encoding of the rest of the transform, using Huffman and RLE
	int zeros = 0;
	bit_file_t *bf = MakeBitFile(fHan, BF_APPEND);
	huffman->setFile(bf);
	huffman->writeTree();
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++) {
			if (i >= PREVIEW || j >= PREVIEW) {
				bool zero = abs(coeff[i*width + j]*C) < .5f;
				if (zero) zeros++;
				if (!zero || (i==stopHeight-1 && j==stopWidth-1)) {
					if (zeros != 0) {
						// RLE: a sequence of zeros has been found
						if (zeros <= 8) {
							unsigned int n = zeros-1;
							BitFilePutBit(1, bf);
							BitFilePutBit(0, bf);
							BitFilePutBitsInt(bf, &n, 3, sizeof(n));
						} else {
							while (zeros > 0) {
								unsigned int n = zeros > 256 ? 255 : zeros-1;
								BitFilePutBit(1, bf);
								BitFilePutBit(1, bf);
								BitFilePutBitsInt(bf, &n, 8, sizeof(n));
								zeros -= 256;
							}
						}
						zeros = 0;
					}
					if (i!=stopHeight-1 || j!=stopWidth-1) {
						// Huffman: write a quantized and then Huffman-encoded value
						unsigned int l = range(round(coeff[i*width + j]*C + M));
						BitFilePutBit(0, bf);
						huffman->writeSymbol(l);
					}
				}
			}
		}
	}
	BitFileFlushOutput(bf, 0);
	delete huffman;

	fclose(fHan);
}
コード例 #4
0
ファイル: sample.c プロジェクト: betamos/Huffman-coding
/***************************************************************************
*   Function   : main
*   Description: This function demonstrates the usage of each of the bit
*                bit file functions.
*   Parameters : argc - the number command line arguments (not used)
*   Parameters : argv - array of command line arguments (not used)
*   Effects    : Writes bit file, reads back results, printing them to
*                stdout.
*   Returned   : EXIT_SUCCESS
***************************************************************************/
int main(int argc, char *argv[])
{
    bit_file_t *bfp;
    FILE *fp;
    int i, numCalls, value;

    if (argc < 2)
    {
        numCalls = NUM_CALLS;
    }
    else
    {
        numCalls = atoi(argv[1]);
    }

    /* create bit file for writing */
    bfp = BitFileOpen("testfile", BF_WRITE);

    if (bfp == NULL)
    {
         perror("opening file");
         return (EXIT_FAILURE);
    }

    /* write chars */
    value = (int)'A';
    for (i = 0; i < numCalls; i++)
    {
        printf("writing char %c\n", value);
        if(BitFilePutChar(value, bfp) == EOF)
        {
            perror("writing char");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }

        value++;
    }

    /* write single bits */
    value = 0;
    for (i = 0; i < numCalls; i++)
    {
        printf("writing bit %d\n", value);
        if(BitFilePutBit(value, bfp) == EOF)
        {
            perror("writing bit");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }

        value = 1 - value;
    }

    /* write ints as bits */
    value = 0x11111111;
    for (i = 0; i < numCalls; i++)
    {
        printf("writing bits %0X\n", (unsigned int)value);
        if(BitFilePutBits(bfp, &value,
            (unsigned int)(8 * sizeof(int))) == EOF)
        {
            perror("writing bits");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }

        value += 0x11111111;
    }

    /* close bit file */
    if (BitFileClose(bfp) != 0)
    {
         perror("closing file");
         return (EXIT_FAILURE);
    }
    else
    {
        printf("closed file\n");
    }

    /* reopen file for appending */
    bfp = BitFileOpen("testfile", BF_APPEND);

    if (bfp == NULL)
    {
         perror("opening file");
         return (EXIT_FAILURE);
    }

    /* append some chars */
    value = (int)'A';
    for (i = 0; i < numCalls; i++)
    {
        printf("appending char %c\n", value);
        if(BitFilePutChar(value, bfp) == EOF)
        {
            perror("appending char");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }

        value++;
    }

    /* write some bits from an integer */
    value = 0x111;
    for (i = 0; i < numCalls; i++)
    {
        printf("writing 12 bits from an integer %03X\n", (unsigned int)value);
        if(BitFilePutBitsInt(bfp, &value, 12, sizeof(value)) == EOF)
        {
            perror("writing bits from an integer");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }

        value += 0x111;
    }

    /* convert to normal file */
    fp = BitFileToFILE(bfp);

    if (fp == NULL)
    {
         perror("converting to stdio FILE");
         return (EXIT_FAILURE);
    }
    else
    {
        printf("converted to stdio FILE\n");
    }

    /* append some chars */
    value = (int)'a';
    for (i = 0; i < numCalls; i++)
    {
        printf("appending char %c\n", value);
        if(fputc(value, fp) == EOF)
        {
            perror("appending char to FILE");
            if (fclose(fp) == EOF)
            {
                 perror("closing stdio FILE");
            }
            return (EXIT_FAILURE);
        }

        value++;
    }

    /* close file */
    if (fclose(fp) == EOF)
    {
         perror("closing stdio FILE");
         return (EXIT_FAILURE);
    }

    /* now read back writes */

    /* open bit file */
    bfp = BitFileOpen("testfile", BF_READ);

    if (bfp == NULL)
    {
         perror("reopening file");
         return (EXIT_FAILURE);
    }

    /* read chars */
    for (i = 0; i < numCalls; i++)
    {
        value = BitFileGetChar(bfp);
        if(value == EOF)
        {
            perror("reading char");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }
        else
        {
            printf("read %c\n", value);
        }
    }

    /* read single bits */
    for (i = 0; i < numCalls; i++)
    {
        value = BitFileGetBit(bfp);
        if(value == EOF)
        {
            perror("reading bit");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }
        else
        {
            printf("read bit %d\n", value);
        }
    }

    /* read ints as bits */
    for (i = 0; i < numCalls; i++)
    {
        if(BitFileGetBits(bfp, &value, (unsigned int)(8 * sizeof(int))) == EOF)
        {
            perror("reading bits");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }
        else
        {
            printf("read bits %0X\n", (unsigned int)value);
        }
    }

    if (BitFileByteAlign(bfp) == EOF)
    {
        fprintf(stderr, "failed to align file\n");
        if (0 != BitFileClose(bfp))
        {
            perror("closing bitfile");
        }
        return (EXIT_FAILURE);
    }
    else
    {
        printf("byte aligning file\n");
    }

    /* read appended characters */
    for (i = 0; i < numCalls; i++)
    {
        value = BitFileGetChar(bfp);
        if(value == EOF)
        {
            perror("reading char");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }
        else
        {
            printf("read %c\n", value);
        }
    }

    /* read some bits into an integer */
    for (i = 0; i < numCalls; i++)
    {
        value = 0;
        if(BitFileGetBitsInt(bfp, &value, 12, sizeof(value)) == EOF)
        {
            perror("reading bits from an integer");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }
        else
        {
            printf("read 12 bits into an integer %03X\n", (unsigned int)value);
        }
    }

    /* convert to stdio FILE */
    fp = BitFileToFILE(bfp);

    if (fp == NULL)
    {
         perror("converting to stdio FILE");
         return (EXIT_FAILURE);
    }
    else
    {
        printf("converted to stdio FILE\n");
    }

    /* read append some chars */
    value = (int)'a';
    for (i = 0; i < numCalls; i++)
    {
        value = fgetc(fp);
        if(value == EOF)
        {
            perror("stdio reading char");
            if (0 != BitFileClose(bfp))
            {
                perror("closing bitfile");
            }
            return (EXIT_FAILURE);
        }
        else
        {
            printf("stdio read %c\n", value);
        }
    }

    /* close file */
    if (fclose(fp) == EOF)
    {
         perror("closing stdio FILE");
         return (EXIT_FAILURE);
    }

    return(EXIT_SUCCESS);
}