Update version info for release v4.6.1 (#2122)
[WRF.git] / external / io_grib1 / WGRIB / flt2ieee.c
blobabb63979d97316605bb30491fd48a74805a9ef2e
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <math.h>
4 #include <float.h>
5 #include "grib.h"
7 /*
8 * convert a float to an ieee single precision number v1.1
9 * (big endian)
10 * Wesley Ebisuzaki
12 * bugs: doesn't handle subnormal numbers
13 * bugs: assumes length of integer >= 25 bits
16 int flt2ieee(float x, unsigned char *ieee) {
18 int sign, exp;
19 unsigned int umant;
20 double mant;
22 if (x == 0.0) {
23 ieee[0] = ieee[1] = ieee[2] = ieee[3] = 0;
24 return 0;
27 /* sign bit */
28 if (x < 0.0) {
29 sign = 128;
30 x = -x;
32 else sign = 0;
33 mant = frexp((double) x, &exp);
35 /* 2^24 = 16777216 */
37 umant = mant * 16777216 + 0.5;
38 if (umant >= 16777216) {
39 umant = umant / 2;
40 exp++;
42 /* bit 24 should be a 1 .. not used in ieee format */
44 exp = exp - 1 + 127;
46 if (exp < 0) {
47 /* signed zero */
48 ieee[0] = sign;
49 ieee[1] = ieee[2] = ieee[3] = 0;
50 return 0;
52 if (exp > 255) {
53 /* signed infinity */
54 ieee[0] = sign + 127;
55 ieee[1] = 128;
56 ieee[2] = ieee[3] = 0;
57 return 0;
59 /* normal number */
61 ieee[0] = sign + (exp >> 1);
63 ieee[3] = umant & 255;
64 ieee[2] = (umant >> 8) & 255;
65 ieee[1] = ((exp & 1) << 7) + ((umant >> 16) & 127);
66 return 0;