⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 char.c

📁 本程序可以对文件进行算术编码处理 解码处理等
💻 C
字号:
/******************************************************************************
File:		char.c

Authors: 	John Carpinelli   (johnfc@ecr.mu.oz.au)
	 	Wayne Salamonsen  (wbs@mundil.cs.mu.oz.au)

Purpose:	Data compression using a char-based model and revised 
		arithmetic coding method.

Based on: 	A. Moffat, R. Neal, I.H. Witten, "Arithmetic Coding Revisted",
		Proc. IEEE Data Compression Conference, Snowbird, Utah, 
		March 1995.


Copyright 1995 John Carpinelli and Wayne Salamonsen, All Rights Reserved.

These programs are supplied free of charge for research purposes only,
and may not sold or incorporated into any commercial product.  There is
ABSOLUTELY NO WARRANTY of any sort, nor any undertaking that they are
fit for ANY PURPOSE WHATSOEVER.  Use them at your own risk.  If you do
happen to find a bug, or have modifications to suggest, please report
the same to Alistair Moffat, alistair@cs.mu.oz.au.  The copyright
notice above and this statement of conditions must remain an integral
part of each and every copy made of these files.

******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "stats.h"
#include "coder.h"
#ifdef SYSV
#include <sys/times.h>
#include <limits.h>
#endif

#define ENCODE          0
#define DECODE          1
#define BUFFER_SIZE	512		/* size of file input buffer */
#define END_OF_MESSAGE	256		/* end of message symbol */
#define MAGICNO         "123c"         	/* Magic Number for files */
#define MAGICNO_LENGTH	4		/* length of magic number */
#define CHAR_CONTEXT	256  		/* length of character contexts */
#define BREAK_INTERVAL	10000		/* every round off to bit boundary */


/* function prototypes */
void encode_file(unsigned char tempstring[], int templength);
void decode_file();
void print_results(int operation);


/* global variables */
int verbose=0;			/* flag set if stats are to be printed */


/* 
 * parse command line arguments. Decide whether to decode or encode
 * and optional memory size. Also sets filename to stdin if none specified 
 */
int main(int argc, char *argv[])
{	
    int i;			/* a counter */
    int what = ENCODE;		/* flag as to whether to encode or decode */
    unsigned char tempstore[MAGICNO_LENGTH];	/* stores magic number */
    int templength=0;		/* number of magic number bytes read */
    int	selected = -1;		/* stores if decode set at command line */

    /* parse command line arguments. Sets up whether to decode or encode
       and optional memory size. Also sets filename to stdin. */
    for (i=1; i<argc; ) 
    {
	if (argv[i][0] == '-') 
	{
	    switch(argv[i][1]) {
	      case 'e':		/* do encode */
		selected = ENCODE;
		i++;
		break;
	      case 'd':		/* do decode */
		selected = DECODE;
		i++;
		break;
	      case 'v':		/* set verbose flag to print stats */
		verbose=1;
		i++;
		break;
	      case 'f':		/* set number of F bits */
		i++;
		f_bits=atoi(argv[i]);
		max_frequency=1<<f_bits;
		i++;
		break;
	      default:		/* incorrect args */
		fprintf(stderr,"usage: %s [-e | -d] [-v] [-f n] [file]\n", 
			argv[0]);
		exit(1);
	    }
	}
	else if (freopen(argv[i++], "r", stdin) == (FILE *)NULL) 
	{
	    fprintf(stderr, "%s: cannot read %s\n",
		    argv[0], argv[--i]);
	    exit(1);
	}
    }
    
    /* check if f_bits is within allowable range */
    if (f_bits < MIN_F_BITS || f_bits > MAX_F_BITS)
    {
	fprintf(stderr, "number of f bits must be between %d and %d\n",
		MIN_F_BITS, MAX_F_BITS);
	exit(1);
    }

    /* Check input file for Magic Number. */
    if (selected != ENCODE)
    {
 	templength=fread(tempstore, 1, MAGICNO_LENGTH, stdin);
	bytes_input += templength;
	if (memcmp(tempstore, MAGICNO, MAGICNO_LENGTH) == 0)
	    what = DECODE;
	else if (selected == DECODE)
	{
	    fprintf(stderr, "Bad Magic Number\n");
	    exit(1);
	}
    }
	
    if (what == ENCODE)	/* do ENCODE */
    {
	/* print magic number in output */
	fwrite(MAGICNO, 1, MAGICNO_LENGTH, stdout);
	bytes_output += MAGICNO_LENGTH;
	
	/* print number of f_bits being used in output */
	putc(f_bits, stdout);
	bytes_output += 1;

	encode_file(tempstore, templength);
    }
    else			/* do DECODE */
    {
	/* get number of f_bits to be used and store in f_bits */
	f_bits=getc(stdin);
	max_frequency=1<<f_bits;
	bytes_input++;
	decode_file();
    }

    if (verbose)
	print_results(what);
    return 0;			/* exited cleanly */
}



/*
 *
 * print the results of compressing/decompressing a file
 *
 */
void print_results(int operation)
{
    if (operation == ENCODE)
	fprintf(stderr, "Input File Size        : %10u bytes\n", bytes_input);
    fprintf(stderr, "Output File Size       : %10u bytes\n", bytes_output);
    if ((operation == ENCODE) && (bytes_input > 0))
	fprintf(stderr, "Compression            : %10.3f bpc (%0.2f%%) \n", 
		8.0 * bytes_output / bytes_input, 
		(float) bytes_output / bytes_input * 100);

    /* only provide timing details if "times" function is available */
#ifdef SYSV
{
    struct tms cpu_usage;
    float cpu_used, comp_rate;

    times(&cpu_usage);    	/* determine the cpu time used */
    cpu_used = ((float) cpu_usage.tms_utime) / sysconf(_SC_CLK_TCK);

    if (cpu_used == 0)
	comp_rate = 0;
    else
    {
        if (operation == ENCODE)
	    comp_rate = ((float) bytes_input) / (1024 * cpu_used);
        else
	    comp_rate = ((float) bytes_output) / (1024 * cpu_used);
    }

    fprintf(stderr, "Compression time       : %10.2f seconds (%0.2f Kb/s)\n",
	    cpu_used, comp_rate);
}
#endif
}



/*
 *
 * compress a file, and output to stdout
 *
 */
void encode_file(unsigned char tempstring[], int templength)
{
    int		i, cur_char;
    context	*characters;

    /* initialise character context */
    characters = create_context(CHAR_CONTEXT+1, STATIC);
    for (i=0; i < CHAR_CONTEXT; i++)
	install_symbol(characters, i);
    install_symbol(characters, END_OF_MESSAGE);

    /* copy first chars read to check magic no. into buffer for encoding */
    start_encode();
    startoutputtingbits();

    for (i=0; i<templength; i++)
	encode(characters, tempstring[i]);
   
    while ((cur_char = getchar()) != EOF)
    {
	encode(characters, cur_char);

	bytes_input++;
	if (bytes_input % BREAK_INTERVAL == 0)
	{
	    finish_encode();
	    start_encode();
	}
    }

    encode(characters, END_OF_MESSAGE);	/* encode end of message */
    finish_encode();
    doneoutputtingbits();
}


/*
 *
 * decode a compressed file to stdout
 *
 */

void decode_file()
{
    int i, symbol;
    context *characters;

    /* initialise character context */
    characters = create_context(CHAR_CONTEXT+1, STATIC);
    for (i=0; i < CHAR_CONTEXT; i++)
	install_symbol(characters, i);
    install_symbol(characters, END_OF_MESSAGE);

    start_decode();
    startinputtingbits();
 
    for (;;)
    {
	symbol=decode(characters);
	if (symbol == END_OF_MESSAGE)
	    break;

	putchar(symbol);
	bytes_output ++;

	if (bytes_output % BREAK_INTERVAL == 0)
	{
	    finish_decode();
	    start_decode();
	}
    }
    finish_decode();
    doneinputtingbits();
}

















⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -