[comp.lang.c] Here's an IEEE to int routine

kohli@gemed (Jim Kohli, but my friends call me) (09/22/89)

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

/****************************************************************
 * F.P. numbers are assumed normalized.  Note: magnitude        *
 * values in excess of sizeof(int) precision are mathematically *
 * limited to sizeof(int)                                       *
 *                                                              *
 *                          Jim Kohli                           *
 *                          GE Medical Systems                  *
 ****************************************************************/

/* No copyright is expressed or implied, nor is accuracy guaranteed */
                 /* but it works for me */

IEEE_TO_INT( r1, r2, n, round)
unsigned long *r1;      /* really IEEE floating point input */
int *r2;                /* integer output */
long int *n;            /* # of numbers to convert, * so F77 callable */
long int *round;        /* if non-zero, round x.5->x+1, else truncate only */
{
int i,sign;
unsigned long t;
float x,rounder,exponent,mantissa;

rounder = *round ? 0.5 : 0.0;

for (i = 0; i < (* n) ; i++) {
    t = r1[i];
    if (!t) r2[i] = 0;
    else {
            /* Get exponent and remove bias of 126 (normal to 1.0) */
        exponent = (float)((t >> 23) & 0xff) - 126.0;

            /* Note: we gain a bit of precision in the mantissa */
        mantissa = (float)((t & 0x007fffff) | 0x00800000);

            /* get the number */
        x = (mantissa/(float)0x00ffffff)*pow(2.0,exponent) + rounder;

            /* Combine results, don't forget the mantissa sign bit */
        r2[i] = (t & 0x80000000) ? -(int)x : (int)x;
        }
    }
}