view tools/ftos.c @ 0:5242703e91d3 tip

Initial checkin for AIM92 aimR8.2 (last updated May 1997).
author tomwalters
date Fri, 20 May 2011 15:19:45 +0100
parents
children
line wrap: on
line source
/*
  ftos.c        binary float-to-short conversion.
 --------

*/

#include <stdio.h>
#include <math.h>
#include "options.h"

char applic[]     = "float to short data-type conversion." ;

static char *helpstr, *errstr ;

static Options option[] = {
    {   "help"      ,   "off"       ,  &helpstr     ,   "help"          ,  DEBUG     },
    {   "error"     ,   "off"       ,  &errstr      ,   "print overflow and quantization errors"  ,  VAL  },
   ( char * ) 0 } ;


#define MAX           32767.
#define MIN        ( -32767. )

main(argc, argv)
int   argc ;
char *argv[] ;
{
    FILE  *fp ;
    float  X  ;
    short  Y  ;
    int    i  ;
    float  min = MAX, fmin ;
    float  max = MIN, fmax ;
    float  quant, maxquant, sumquant=0 ;

    fp = openopts( option,argc,argv ) ;
    if ( !isoff( helpstr ) )
	helpopts( helpstr, argv[0], applic, option ) ;

    if ( isoff( errstr ) ) {

	while ( fread( &X, sizeof(float), 1, fp ) ) {
	    Y = (short)X ;
	    fwrite( &Y, sizeof(short), 1, stdout);
	}
    }

    else {

	for ( i = 0 ; fread( &X, sizeof(float), 1, fp ) ; i++ ) {
	    if ( X > max ) max = X ;
	    if ( X < min ) min = X ;
	    quant = ( X - (int)X ) / (int)( 1 + X ) ;
	    sumquant += quant ;
	    if ( quant > maxquant ) maxquant = quant ;
	    Y = (short)X ;
	    fwrite( &Y, sizeof(short), 1, stdout);
	}

	if ( max > MAX || min < MIN ) {

	    if ( max > MAX )  fmax = MAX / max ;
	    if ( min < MIN )  fmin = MIN / min ;

	    if ( fmax < fmin ) fprintf( stderr, "16-bit overflow  (scale down by a factor < %f\n", fmax ) ;
	    else               fprintf( stderr, "16-bit underflow  (scale down by a factor < %f\n", fmin ) ;
	}
	fprintf( stderr, "max  quantization error = %f\n", maxquant   ) ;
	fprintf( stderr, "mean quantization error = %f\n", sumquant/i ) ;
    }

    fclose(fp);
    exit(0);
}